<?xml version="1.0" encoding="UTF-8"?>
<!-- -*- coding: utf-8 -*-  -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg" xml:lang="en">
<head>                            
  <title>Unix Toolbox</title>
  <meta name="author" content="Colin Barschel c@cb.vu"/>
  <meta name="copyright" content="Copyright © 2007-2008 Colin Barschel. Some rights reserved under Creative Commons [Attribution - Share Alike]"/>
  <meta name="description" content="A collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users, a compact and practical reference."/>
  <meta name="abstract" content="Unix Toolbox a compact and practical reference for sysadmins and advanced users."/>
  <meta name="subject" content="Unix Toolbox revision 12"/>
  <meta name="keywords" content="Unix Toolbox, Unix tools, Unix, FreeBSD, Linux, commands list, sysadmin, practical guide, advanced reference, common Linux tasks, syntax reminder, howtos, ssh tunnels, rsync, ssl certificates"/>
  <style type="text/css">
/* basic CSS common to all media */
html {
    margin: 0;
}
body {
    padding: 0;
    font-family: verdana, arial, sans-serif;
    font-size: 90%;
    counter-reset: chapter section;
}
div.title {
    text-transform: uppercase;
    padding: 1em 0;
    text-align: center;
    font-size: 220%;
    font-weight: bold;
    letter-spacing: .22em;
}
h1, h2, h3 div.title {
    font-family: verdana, sans-serif;
}
h1 {
    text-transform: uppercase;
    font-size: 150%;
    letter-spacing: .15em;
    counter-reset: section;
    string-set: chaptertitle content();
}
h2 {
    font-size: 120%;
    letter-spacing: .10em;
}
h3, h4 {
    font-size: 100%;
    line-height:1em;
    letter-spacing: .07em;
}
h4 {
    font-style: italic;
    font-weight: normal;
    margin: 1em 0 0.5em 0;
}
pre {
    padding: 0.1em 0em 0.1em 1em;
}
div.menu a {
    font-weight: normal;
    text-decoration: none;
}
h1:before {
    content: counter(chapter) " ";
    counter-increment: chapter;
}
h2:before {
    counter-increment: section;
    content: counter(chapter) "." counter(section) " ";
}
/* Not implemented in browsers yet */
a.xref:after { 
    content: " " target-counter(attr(href, url), chapter) "."
    target-counter(attr(href, url), section); 
}
div.changestyle {
    padding-top: 1em;
}

@media screen, handheld {
/* Menu on the right for screen media */
/* including some IE6 hacks */
    body {
        padding: 0;
        margin: 1em 13em 0em 2em;
    }	
    html&gt;body {
        margin: 1em 13em 0em 2em;
    }
    body&gt;div.menu {
        position: fixed;
    }
    body&gt;div.changestyle {
        position: fixed;
    }
    div.menu { 
        position: absolute;
        z-index: 2;
        width: 10.2em; height: auto;
        top: 0.4em; right: 1em; bottom: 0.8em; left: auto;
    }
    div.changestyle {
        font-size: 80%;
        font-weight: normal;
        position: absolute;
        z-index: 2;
        width: 10.2em; height: auto;
        bottom: 0;
    }
    ol.toc, ol.toc li  {
        margin: 0;
        list-style-type: none;
        padding: 0.13em 0;
        text-indent: 0;
        text-align: left;
    }
    p.last {
        padding-top: 5em;
    }
    .fn {
        display: none;
        counter-increment: footnote
    }
}

@media print {
/* layout */
/* Menu as TOC for print */
    body {
        font-size: 88%;
    }	
    div.title {
        padding: 0.5em 0 2em 0;
    }
    div {
        text-align: justify;
    }
    
    h3 {
        margin-bottom: 1em;
    }
    pre {
        font-size: 90%;
        margin: 0.4em 0;
        padding: 0.2em 0 0.2em 0.4em;
        text-align: left;
    }
    a {
	text-decoration: none;
    }
    p.xrefp {  /* links below h1 headers */
        padding-top: 0;
        margin: -0.9em 0 1.3em 0;
        page-break-inside: avoid;
        page-break-after: avoid;
    }
    a.xrefp {
        font-weight: normal;
        text-decoration: none;
    }
    ol.toc li  {
        list-style-type: decimal;
        margin: 0;
        padding: 0.25em 0;
    }
    ol.toc  {
        margin: 0 0 0 2.2em;
        list-style-position: outside;
        font-weight: normal;
        list-style-type: decimal;
        padding: 4em 0;
    }
    ol.toc a::after {
        content: leader(' . ') target-counter(attr(href), page);
    }
/*
a.xref:after { 
    content: " [" target-counter(attr(href, url), chapter) "."
    target-counter(attr(href, url), section) " page " 
    target-counter(attr(href, url), page) "]"; 
}
*/
    a.xref:after { 
        content: " (page " target-counter(attr(href, url), page) ")"; 
    }
    a.xrefp:after { 
        content: " (p"target-counter(attr(href, url), page)")"; 
    }
    h1, h2, h3, h4, h5 { 
        page-break-after: avoid;
    }
    div.footerfirst, div.footerlast {
        position: absolute;
        bottom: 0;
    }
    div.main {
        page-break-before: always;
    }
    div.pb {
        page-break-after: always;
    }
    div.changestyle, p.copyright, span.web {
        display: none;
    }
    div#sysinfo {
        margin-top: -1.5em;
    }
    p.last {
        padding-top: 2em;
    }
    .fn {
        display: prince-footnote;
        counter-increment: footnote;
        font-size: 80%;
    }
    .fn::footnote-call {
        content: counter(footnote);
        font-size: 80%;
        vertical-align: super;
        line-height: none
    }
    .fn::footnote-marker {
        list-style-position: inside;
    }
}
@page {
    size: A4 portrait;
    margin: 16mm 14mm 14mm 12mm;
    padding: 0mm 0 5mm 0;
    @footnotes {
	border-top: solid #000040 thin;
	padding-top: 0.22em;
        padding-left: 1.2em;
        font-family: verdana, sans-serif;
    }
    @bottom-center {
        padding: 0 0 5mm 0;
        content: counter(page);
        font-family: verdana, sans-serif;
        font-size: 88%;
    }
    @top {
        padding-top: 5mm;
	content: "— " string(chaptertitle) " —";
        font-family: verdana, sans-serif;
    }
}
@page :first {
    padding: 0;
    @bottom-center {
        content: normal;
    }
    @top {
        content: normal;
    }
}

</style>
<style type="text/css" title="default">
@media screen, handheld, print {
/* Colors only */
html {
    background-color: white;
    color: black;
}
h1 {
    background-color: #000040;
    color: white;
}
h3, h4, div.title, h2, a:link, a:visited, .cmt {
    background-color: transparent;
    color: #000040;
}
pre {
    background-color: #F6F6FC;
}
pre, code { 
    color: #003300;
}
a:hover, .pp {
    color: #D55500;
}
a:active {
    color: green;
}
.keyword {
    color:#0000FF;
}
}
@media print {
/* print only colors */
pre, code { 
    color: #000;
}
a:link, a:visited, .cmt {
    background-color: transparent;
    color: #000060;
}
}
</style>
<style type="text/css" title="inverse">
@media screen, handheld {
/* Colors only */
html {
    background-color: black;
    color: Gainsboro;
}
h1 {
    background-color: #ffffcd;
    color: black;
}
h3, h4, div.title, h2, a:link, a:visited, .cmt {
    background-color: transparent;
    color: #ffffcd;
}
pre {
    background-color: #090903;
}
pre, code { 
    color: #ffc3ff;
}
a:hover, .pp {
    color: #2aaaff;
}
a:active {
    color: orange;
}
.keyword {
    color:#ff0000;
}
}
</style>

  <!-- Script to change the color of the site via the above two styles and
       save the selection into a cookie. The cookie is only generated when
       either the link "white" or "black" is clicked -->

  <!-- This does not word on Safari and Konqueror. Can someone fix it? -->
<script type="text/javascript">
/*<![CDATA[*/

function initCSS() {
  var cookie = readCookie("style");
  var title = cookie ? cookie : "default";
  setActiveStyle(title);
}

function setActiveStyle(title) {
  var j = document.getElementsByTagName("style");
  for(var i=1; i < j.length; i++) { // bypass the first (main) style
    j[i].disabled = true;
    if(j[i].getAttribute("title") == title) {
        j[i].disabled = false;
    }
  }
}

/* Only create a cookie when the link is clicked */
function setActiveStyleLink(title) {
  setActiveStyle(title)
  createCookie("style", title, 365);
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

window.onload = initCSS();

/*]]>*/
</script>

</head>
<body>

<div class="title">Unix Toolbox</div>
<div class="abstract">
This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users. This is a practical guide with concise explanations, however the reader is supposed to know what s/he is doing.<br/><br/>
</div>
<div class="footerfirst">
Unix Toolbox revision 12<br/>
The latest version of this document can be found at <a href="http://cb.vu/unixtoolbox.xhtml">http://cb.vu/unixtoolbox.xhtml</a>. Replace .xhtml on the link with <a href="http://cb.vu/unixtoolbox.pdf">.pdf</a> for the PDF version and with <a href="http://cb.vu/unixtoolbox.book.pdf">.book.pdf</a> for the booklet version. On a duplex printer the booklet will create a small book ready to bind. <span class="web">This XHTML page can be converted into a nice PDF document with a CSS3 compliant application (see the <a class="xref" href="#bourneexample">script example</a>).</span> See also the <a href="http://cb.vu/unixtoolbox">about page</a>.<br/>
Error reports and comments are most welcome - <a href="mailto:c\at\cb.vu">c@cb.vu</a> Colin Barschel.
<p class="copyright">© <a href="mailto:c_at_cb.vu">Colin Barschel</a> 2007-2008. <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Some rights reserved under Creative Commons</a>.
</p>
</div> 

<div class="menu">
<ol class="toc">
  <li><a href="#sysinfo">System</a></li>
  <li><a href="#processes">Processes</a></li>
  <li><a href="#filesystem">File System</a></li>
  <li><a href="#network">Network</a></li>
  <li><a href="#ssh">SSH SCP</a></li>
  <li><a href="#vpn">VPN with SSH</a></li>
  <li><a href="#rsync">RSYNC</a></li>
  <li><a href="#sudo">SUDO</a></li>
  <li><a href="#crypt">Encrypt Files</a></li>
  <li><a href="#cryptpart">Encrypt Partitions</a></li>
  <li><a href="#certs">SSL Certificates</a></li>
  <li><a href="#cvs">CVS</a></li>
  <li><a href="#svn">SVN</a></li>
  <li><a href="#other">Useful Commands</a></li>
  <li><a href="#software">Install Software</a></li>
  <li><a href="#convert">Convert Media</a></li>
  <li><a href="#printing">Printing</a></li>
  <li><a href="#databases">Databases</a></li>
  <li><a href="#quota">Disk Quota</a></li>
  <li><a href="#shells">Shells</a></li>
  <li><a href="#scripting">Scripting</a></li>
  <li><a href="#programming">Programming</a></li>
  <li><a href="#onlinehelp">Online Help</a></li>
</ol>
<br/>
<div class="changestyle">
<a href="#" onclick="setActiveStyleLink('default'); return false;">
<svg:svg width="15" height="10" viewBox="0 0 310 210">
<svg:rect x="5" y="5" width="300" height="200" style="stroke: black; stroke-width: 7; fill: white;"/>
<svg:line x1="25" y1="55" x2="280" y2="55" style="stroke: black; stroke-width: 7;"/>
<svg:line x1="25" y1="100" x2="280" y2="100" style="stroke: black; stroke-width: 7;"/>
<svg:line x1="25" y1="148" x2="280" y2="148" style="stroke: black; stroke-width: 7;"/>
</svg:svg> white
</a>
<a href="#" onclick="setActiveStyleLink('inverse'); return false;">
<svg:svg width="15" height="10" viewBox="0 0 310 210">
<svg:rect x="5" y="5" width="300" height="200" style="stroke: white; stroke-width: 7; fill: black;"/>
<svg:line x1="25" y1="55" x2="280" y2="55" style="stroke: white; stroke-width: 10;"/>
<svg:line x1="25" y1="100" x2="280" y2="100" style="stroke: white; stroke-width: 10;"/>
<svg:line x1="25" y1="148" x2="280" y2="148" style="stroke: white; stroke-width: 10;"/>
</svg:svg> black
</a>
</div> <!-- end change style links -->
</div> <!-- end menu -->
<div class="pb"/>
 <!-- <div class="main"> Every chapter is inside a div block for easy XML parsing -->
<div id="sysinfo"><h1><a>System</a></h1>
<p class="xrefp"><a class="xrefp" href="#hardwareinfo">Hardware</a> | <a class="xrefp" href="#loadstats">Statistics</a> | <a class="xrefp" href="#users">Users</a> | <a class="xrefp" href="#limits">Limits</a> | <a class="xrefp" href="#runlevels">Runlevels</a> | <a class="xrefp" href="#resetpasswd">root password</a> | <a class="xrefp" href="#compilekernel">Compile kernel</a></p>
Running kernel and system information
<pre># uname -a                           <span class="cmt"># Get the kernel version (and BSD version)</span>
# lsb_release -a                     <span class="cmt"># Full release info of any LSB distribution</span>
# cat /etc/SuSE-release              <span class="cmt"># Get SuSE version</span>
# cat /etc/debian_version            <span class="cmt"># Get Debian version</span>
</pre>
Use /etc/<code>DISTR</code>-release with <code>DISTR=</code> lsb (Ubuntu), redhat, gentoo, mandrake, sun (Solaris), and so on.
<pre># uptime                             <span class="cmt"># Show how long the system has been running + load</span>
# hostname                           <span class="cmt"># system's host name</span>
# hostname -i                        <span class="cmt"># Display the IP address of the host.</span>
# man hier                           <span class="cmt"># Description of the file system hierarchy</span>
# last reboot                        <span class="cmt"># Show system reboot history</span>
</pre>
<h2 id="hardwareinfo">Hardware Informations</h2>
Kernel detected hardware
<pre># dmesg                              <span class="cmt"># Detected hardware and boot messages</span>
# lsdev                              <span class="cmt"># information about installed hardware</span>
# dd if=/dev/mem bs=1k skip=768 count=256 2&gt;/dev/null | strings -n 8 <span class="cmt"># Read BIOS</span>
</pre>
<h3>Linux</h3>
<pre># cat /proc/cpuinfo                  <span class="cmt"># CPU model</span>
# cat /proc/meminfo                  <span class="cmt"># Hardware memory</span>
# grep MemTotal /proc/meminfo        <span class="cmt"># Display the physical memory</span>
# watch -n1 'cat /proc/interrupts'   <span class="cmt"># Watch changeable interrupts continuously</span>
# free -m                            <span class="cmt"># Used and free memory (-m for MB)</span>
# cat /proc/devices                  <span class="cmt"># Configured devices</span>
# lspci -tv                          <span class="cmt"># Show PCI devices</span>
# lsusb -tv                          <span class="cmt"># Show USB devices</span>
# lshal                              <span class="cmt"># Show a list of all devices with their properties</span>
# dmidecode                          <span class="cmt"># Show DMI/SMBIOS: hw info from the BIOS</span>
</pre>
<h3>FreeBSD</h3>
<pre># sysctl hw.model                    <span class="cmt"># CPU model</span>
# sysctl hw                          <span class="cmt"># Gives a lot of hardware information</span>
# sysctl vm                          <span class="cmt"># Memory usage</span>
# dmesg | grep "real mem"            <span class="cmt"># Hardware memory</span>
# sysctl -a | grep mem               <span class="cmt"># Kernel memory settings and info</span>
# sysctl dev                         <span class="cmt"># Configured devices</span>
# pciconf -l -cv                     <span class="cmt"># Show PCI devices</span>
# usbdevs -v                         <span class="cmt"># Show USB devices</span>
# atacontrol list                    <span class="cmt"># Show ATA devices</span>
</pre>
<h2 id="loadstats">Load, statistics and messages</h2>
The following commands are useful to find out what is going on on the system.
<pre># top                                <span class="cmt"># display and update the top cpu processes</span>
# mpstat 1                           <span class="cmt"># display processors related statistics</span>
# vmstat 2                           <span class="cmt"># display virtual memory statistics</span>
# iostat 2                           <span class="cmt"># display I/O statistics (2 s intervals)</span>
# systat -vmstat 1                   <span class="cmt"># BSD summary of system statistics (1 s intervals)</span>
# systat -tcp 1                      <span class="cmt"># BSD tcp connections (try also -ip)</span>
# systat -netstat 1                  <span class="cmt"># BSD active network connections</span>
# systat -ifstat 1                   <span class="cmt"># BSD network traffic through active interfaces</span>
# systat -iostat 1                   <span class="cmt"># BSD CPU and and disk throughput</span>
# tail -n 500 /var/log/messages      <span class="cmt"># Last 500 kernel/syslog messages</span>
# tail /var/log/warn                 <span class="cmt"># System warnings messages see syslog.conf</span>
</pre>
<h2 id="users">Users</h2>
<pre># id                                 <span class="cmt"># Show the active user id with login and group</span>
# last                               <span class="cmt"># Show last logins on the system</span>
# who                                <span class="cmt"># Show who is logged on the system</span>
# groupadd admin                     <span class="cmt"># Add group "admin" and user colin (Linux/Solaris)</span>
# useradd -c "Colin Barschel" -g admin -m colin
# userdel colin                      <span class="cmt"># Delete user colin (Linux/Solaris)</span>
# adduser joe                        <span class="cmt"># FreeBSD add user joe (interactive)</span>
# rmuser joe                         <span class="cmt"># FreeBSD delete user joe (interactive)</span>
# pw groupadd admin                  <span class="cmt"># Use pw on FreeBSD</span>
# pw groupmod admin -m newmember     <span class="cmt"># Add a new member to a group</span>
# pw useradd colin -c "Colin Barschel" -g admin -m -s /bin/tcsh 
# pw userdel colin; pw groupdel admin
</pre>
Encrypted passwords are stored in /etc/shadow for Linux and Solaris and /etc/master.passwd on FreeBSD. If the master.passwd is modified manually (say to delete a password), run <code># pwd_mkdb -p master.passwd</code> to rebuild the database.<br/><br/>
To temporarily prevent logins system wide (for all users but root) use nologin. The message in nologin will be displayed (might not work with ssh pre-shared keys).
<pre># echo "Sorry no login now" &gt; /etc/nologin       <span class="cmt"># (Linux)</span>
# echo "Sorry no login now" &gt; /var/run/nologin   <span class="cmt"># (FreeBSD)</span>
</pre>

<h2 id="limits">Limits</h2>
Some application require higher limits on open files and sockets (like a proxy
web server, database). The default limits are usually too low.
<h3>Linux</h3>
<h4>Per shell/script</h4>
The shell limits are governed by <code>ulimit</code>. The status is checked
with <code>ulimit -a</code>. For example to change the open files limit from
1024 to 10240 do:
<pre># ulimit -n 10240                    <span class="cmt"># This is only valid within the shell</span>
</pre>
The <code>ulimit</code> command can be used in a script to change the limits for the script only.

<h4>Per user/process</h4>
Login users and applications can be configured in <code>/etc/security/limits.conf</code>. For example:
<pre># cat /etc/security/limits.conf
*   hard    nproc   250              <span class="cmt"># Limit user processes</span>
asterisk hard nofile 409600          <span class="cmt"># Limit application open files</span>
</pre>
<h4>System wide</h4>
Kernel limits are set with sysctl. Permanent limits are set in <code>/etc/sysctl.conf</code>.
<pre># sysctl -a                          <span class="cmt"># View all system limits</span>
# sysctl fs.file-max                 <span class="cmt"># View max open files limit</span>
# sysctl fs.file-max=102400          <span class="cmt"># Change max open files limit</span>
# cat /etc/sysctl.conf
fs.file-max=102400                   <span class="cmt"># Permanent entry in sysctl.conf</span>
# cat /proc/sys/fs/file-nr           <span class="cmt"># How many file descriptors are in use</span>
</pre>

<h3>FreeBSD</h3>
<h4>Per shell/script</h4>
Use the command <code>limits</code> in csh or tcsh or as in Linux, use <code>ulimit</code> in an sh or bash shell.
<h4>Per user/process</h4>
The default limits on login are set in <code>/etc/login.conf</code>. An unlimited value is still limited by the system maximal value.
<h4>System wide</h4>
Kernel limits are also set with sysctl. Permanent limits are set in <code>/etc/sysctl.conf</code> or <code>/boot/loader.conf</code>. The syntax is the same as Linux but the keys are different.
<pre># sysctl -a                          <span class="cmt"># View all system limits</span>
# sysctl kern.maxfiles=XXXX          <span class="cmt"># maximum number of file descriptors</span>
kern.ipc.nmbclusters=32768           <span class="cmt"># Permanent entry in /etc/sysctl.conf</span>
kern.maxfiles=65536                  <span class="cmt"># Typical values for Squid</span>
kern.maxfilesperproc=32768
kern.ipc.somaxconn=8192              <span class="cmt"># TCP queue. Better for apache/sendmail</span>
# sysctl kern.openfiles              <span class="cmt"># How many file descriptors are in use</span>
# sysctl kern.ipc.numopensockets     <span class="cmt"># How many open sockets are in use</span>
</pre>
See The <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/configtuning-kernel-limits.html">FreeBSD handbook Chapter 11</a><span class="fn">http://www.freebsd.org/handbook/configtuning-kernel-limits.html</span> for details.

<h3>Solaris</h3>
The following values in <code>/etc/system</code> will increase the maximum file descriptors per proc:
<pre>set rlim_fd_max = 4096               <span class="cmt"># Hard limit on file descriptors for a single proc</span>
set rlim_fd_cur = 1024               <span class="cmt"># Soft limit on file descriptors for a single proc</span>
</pre>

<h2 id="runlevels">Runlevels</h2>
<h3>Linux</h3>
Once booted, the kernel starts <code>init</code> which then starts <code>rc</code> which starts all scripts belonging to a runlevel. The scripts are stored in /etc/init.d and are linked into /etc/rc.d/rcN.d with N the runlevel number.<br/>
The default runlevel is configured in /etc/inittab. It is usually 3 or 5:
<pre># grep default: /etc/inittab                                         
id:3:initdefault:
</pre>
The actual runlevel (the list is shown below) can be changed with <code>init</code>. For example to go from 3 to 5:
<pre># init 5                             <span class="cmt"># Enters runlevel 5</span></pre>
<ul style="list-style-type: none; page-break-inside: avoid;">
  <li>0       Shutdown and halt</li>
  <li>1       Single-User mode (also S)</li>
  <li>2       Multi-user without network</li>
  <li>3       Multi-user with network</li>
  <li>5       Multi-user with X</li>
  <li>6       Reboot</li>
</ul>
Use <code>chkconfig</code> to configure the programs that will be started at boot in a runlevel.
<pre># chkconfig --list                   <span class="cmt"># List all init scripts</span>
# chkconfig --list sshd              <span class="cmt"># Report the status of sshd</span>
# chkconfig sshd --level 35 on       <span class="cmt"># Configure sshd for levels 3 and 5</span>
# chkconfig sshd off                 <span class="cmt"># Disable sshd for all runlevels</span>
</pre>
Debian and Debian based distributions like Ubuntu or Knoppix use the command <code>update-rc.d</code> to manage the runlevels scripts. Default is to start in 2,3,4 and 5 and shutdown in 0,1 and 6.
<pre># update-rc.d sshd defaults          <span class="cmt"># Activate sshd with the default runlevels</span>
# update-rc.d sshd start 20 2 3 4 5 . stop 20 0 1 6 .  <span class="cmt"># With explicit arguments</span>
# update-rc.d -f sshd remove         <span class="cmt"># Disable sshd for all runlevels</span>
# shutdown -h now (or # poweroff)    <span class="cmt"># Shutdown and halt the system</span>
</pre>

<h3>FreeBSD</h3>
The BSD boot approach is different from the SysV, there are no runlevels. The final boot state (single user, with or without X) is configured in <code>/etc/ttys</code>. All OS scripts are located in <code>/etc/rc.d/</code> and in <code>/usr/local/etc/rc.d/</code> for third-party applications. The activation of the service is configured in <code>/etc/rc.conf</code> and <code>/etc/rc.conf.local</code>. The default behavior is configured in <code>/etc/defaults/rc.conf</code>. The scripts responds at least to start|stop|status.
<pre># /etc/rc.d/sshd status
sshd is running as pid 552.
# shutdown now                       <span class="cmt"># Go into single-user mode</span>
# exit                               <span class="cmt"># Go back to multi-user mode</span>
# shutdown -p now                    <span class="cmt"># Shutdown and halt the system</span>
# shutdown -r now                    <span class="cmt"># Reboot</span>
</pre>
The process <code>init</code> can also be used to reach one of the following states level. For example <code># init 6</code> for reboot.
<ul style="list-style-type: none; page-break-inside: avoid;">
  <li>0       Halt and turn the power off (signal <code>USR2</code>)</li>
  <li>1       Go to single-user mode (signal <code>TERM</code>)</li>
  <li>6       Reboot the machine (signal <code>INT</code>)</li>
  <li>c       Block further logins (signal <code>TSTP</code>)</li>
  <li>q       Rescan the ttys(5) file (signal <code>HUP</code>)</li>
</ul>

<h2 id="resetpasswd">Reset root password</h2>
<h3>Linux method 1</h3>
At the boot loader (lilo or grub), enter the following boot option:
<pre>init=/bin/sh</pre>
The kernel will mount the root partition and <code>init</code> will start the bourne shell
instead of <code>rc</code> and then a runlevel. Use the command <code>passwd</code> at the prompt to change the password and then reboot. Forget the single user mode as you need the password for that.<br/>
If, after booting, the root partition is mounted read only, remount it rw:
<pre># mount -o remount,rw /
# passwd                             <span class="cmt"># or delete the root password (/etc/shadow)</span>
# sync; mount -o remount,ro /        <span class="cmt"># sync before to remount read only</span>
# reboot
</pre> 
<h3>FreeBSD method 1</h3>
On FreeBSD, boot in single user mode, remount / rw and use passwd. You can select the single user mode on the boot menu (option 4) which is displayed for 10 seconds at startup. The single user mode will give you a root shell on the / partition.
<pre># mount -u /; mount -a               <span class="cmt"># will mount / rw</span>
# passwd
# reboot
</pre>

<h3>Unixes and FreeBSD and Linux method 2</h3>
Other Unixes might not let you go away with the simple init trick. The solution is to mount the root partition from an other OS (like a rescue CD) and change the password on the disk.
<ul>
  <li>Boot a live CD or installation CD into a rescue mode which will give you a shell.</li>
  <li>Find the root partition with fdisk e.g. fdisk /dev/sda</li>
  <li>Mount it and use chroot:</li>
</ul>
<pre># mount -o rw /dev/ad4s3a /mnt
# chroot /mnt                        <span class="cmt"># chroot into /mnt</span>
# passwd
# reboot
</pre>


<h2 id="kernelmodules">Kernel modules</h2>
<h3>Linux</h3>
<pre># lsmod                              <span class="cmt"># List all modules loaded in the kernel</span>
# modprobe isdn                      <span class="cmt"># To load a module (here isdn)</span>
</pre>
<h3>FreeBSD</h3>
<pre># kldstat                            <span class="cmt"># List all modules loaded in the kernel</span>
# kldload crypto                     <span class="cmt"># To load a module (here crypto)</span>
</pre>
<h2 id="compilekernel">Compile Kernel</h2>
<h3>Linux</h3>
<pre># cd /usr/src/linux
# make mrproper                      <span class="cmt"># Clean everything, including config files</span>
# make oldconfig                     <span class="cmt"># Create a new config file from the current kernel</span>
# make menuconfig                    <span class="cmt"># or xconfig (Qt) or gconfig (GTK)</span>
# make                               <span class="cmt"># Create a compressed kernel image</span>
# make modules                       <span class="cmt"># Compile the modules</span>
# make modules_install               <span class="cmt"># Install the modules</span>
# make install                       <span class="cmt"># Install the kernel</span>
# reboot
</pre>
<h3>FreeBSD</h3>
To modify and rebuild the kernel, copy the generic configuration file to a new name and edit it as needed. It is however also possible to edit the file <code>GENERIC</code> directly.
<pre># cd /usr/src/sys/i386/conf/
# cp GENERIC MYKERNEL
# cd /usr/src
# make buildkernel KERNCONF=MYKERNEL
# make installkernel KERNCONF=MYKERNEL
</pre>
To rebuild the full OS:
<pre># make buildworld                    <span class="cmt"># Build the full OS but not the kernel</span>
# make buildkernel                   <span class="cmt"># Use KERNCONF as above if appropriate</span>
# make installkernel
# reboot
# mergemaster -p                     <span class="cmt"># Compares only files known to be essential</span>
# make installworld
# mergemaster                        <span class="cmt"># Update all configuration and other files</span>
# reboot
</pre>
For small changes in the source, sometimes the short version is enough:
<pre># make kernel world                  <span class="cmt"># Compile and install both kernel and OS</span>
# mergemaster
# reboot
</pre>
</div>

<div id="processes"><h1><a>Processes</a></h1>
<p class="xrefp"><a class="xrefp" href="#ps">Listing</a> | <a class="xrefp" href="#nice">Priority</a> | <a class="xrefp" href="#bgfg">Background/Foreground</a> | <a class="xrefp" href="#top">Top</a> | <a class="xrefp" href="#kill">Kill</a></p>
<h2 id="ps">Listing and PIDs</h2>
Each process has a unique number, the PID. A list of all running process is retrieved with <code>ps</code>.
<pre># ps -auxefw                         <span class="cmt"># Extensive list of all running process</span></pre>
However more typical usage is with a pipe or with <code>pgrep</code>:
<pre># ps axww | grep cron
  586  ??  Is     0:01.48 /usr/sbin/cron -s
# ps aux | grep 'ss[h]'              <span class="cmt"># Find all ssh pids without the grep pid</span>
# pgrep -l sshd                      <span class="cmt"># Find the PIDs of processes by (part of) name</span>
# echo $$                            <span class="cmt"># The PID of your shell</span>
# fuser -va 22/tcp                   <span class="cmt"># List processes using port 22 (Linux)</span>
# fuser -va /home                    <span class="cmt"># List processes accessing the /home partiton</span>
# strace df                          <span class="cmt"># Trace system calls and signals</span>
# truss df                           <span class="cmt"># same as above on FreeBSD/Solaris/Unixware</span>
# history | tail -50                 <span class="cmt"># Display the last 50 used commands</span>
</pre>

<h2 id="nice">Priority</h2>
Change the priority of a running process with <code>renice</code>. Negative numbers have a higher priority, the lowest is -20 and "nice" have a positive value.
<pre># renice -5 586                      <span class="cmt"># Stronger priority</span>
586: old priority 0, new priority -5
</pre>
Start the process with a defined priority with <code>nice</code>. Positive is "nice" or weak, negative is strong scheduling priority. Make sure you know if <code>/usr/bin/nice</code> or the shell built-in is used (check with <code># which nice</code>).
<pre># nice -n -5 top                     <span class="cmt"># Stronger priority (/usr/bin/nice)</span>
# nice -n 5 top                      <span class="cmt"># Weaker priority (/usr/bin/nice)</span>
# nice +5 top                        <span class="cmt"># tcsh builtin nice (same as above!)</span>
</pre>
While nice changes the CPU scheduler, an other useful command <code>ionice</code> will schedule the disk IO. This is very useful for intensive IO application which can bring a machine to its knees while still in a lower priority. The command is only available on Linux (AFAIK). You can select a class (idle - best effort - real time), the man page is short and well explained.
<pre># ionice c3 -p123                    <span class="cmt"># set idle class for pid 123</span>
# ionice -c2 -n0 firefox             <span class="cmt"># Run firefox with best effort and high priority</span>
# ionice -c3 -p$$                    <span class="cmt"># Set the actual shell to idle priority</span>
</pre>
For example last command is very useful to compile (or debug) a large project. Every command launched from this shell will have a lover priority and will not disturb the system. $$ is your shell pid (try echo $$).

<h2 id="bgfg">Background/Foreground</h2>
When started from a shell, processes can be brought in the background and back to the foreground with [Ctrl]-[Z] (^Z), <code>bg</code> and <code>fg</code>. For example start two processes, bring them in the background, list the processes with <code>jobs</code> and bring one in the foreground.
<pre># ping cb.vu &gt; ping.log
^Z                                   <span class="cmt"># ping is suspended (stopped) with [Ctrl]-[Z]</span> 
# bg                                 <span class="cmt"># put in background and continues running</span>
# jobs -l                            <span class="cmt"># List processes in background</span>
[1]  - 36232 Running                       ping cb.vu &gt; ping.log
[2]  + 36233 Suspended (tty output)        top
# fg %2                              <span class="cmt"># Bring process 2 back in foreground</span>
</pre>
Use <code>nohup</code> to start a process which has to keep running when the shell is closed (immune to hangups).
<pre># nohup ping -i 60 &gt; ping.log &amp;
</pre>

<h2 id="top">Top</h2>
The program <code>top</code> displays running information of processes. The program <code>htop</code> from htop.sourceforge.net is a very nice alternative and a more powerful version of top. Runs on Linux and FreeBSD (<code>ports/sysutils/htop/</code>).
<pre># top</pre>
While top is running press the key h for a help overview. Useful keys are:
<ul>
  <li><b>u [user name]</b> To display only the processes belonging to the user. Use + or blank to see all users</li>
  <li><b>k [pid]</b> Kill the process with pid.</li>
  <li><b>1</b> To display all processors statistics (Linux only)</li>
   <li><b>R</b> Toggle normal/reverse sort.</li>
</ul>
<h2 id="kill">Signals/Kill</h2>
Terminate or send a signal with <code>kill</code> or <code>killall</code>.
<pre># ping -i 60 cb.vu &gt; ping.log &amp;
[1] 4712
# kill -s TERM 4712                  <span class="cmt"># same as kill -15 4712</span>
# killall -1 httpd                   <span class="cmt"># Kill HUP processes by exact name</span>
# pkill -9 http                      <span class="cmt"># Kill TERM processes by (part of) name</span>
# pkill -TERM -u www                 <span class="cmt"># Kill TERM processes owned by www</span>
# fuser -k -TERM -m /home            <span class="cmt"># Kill every process accessing /home (to umount)</span>
</pre>
Important signals are:
<ul style="list-style-type: none;">
  <li>1       <code>HUP</code> (hang up)</li>
  <li>2       <code>INT</code> (interrupt)</li>
  <li>3       <code>QUIT</code> (quit)</li>
  <li>9       <code>KILL</code> (non-catchable, non-ignorable kill)</li>
  <li>15     <code>TERM</code> (software termination signal)</li>
</ul>

</div>

<div id="filesystem"><h1><a>File System</a></h1>
<p class="xrefp"><a class="xrefp" href="#diskinfo">Disk info</a> | <a class="xrefp" href="#fsboot">Boot</a> | <a class="xrefp" href="#mountpoints">Disk usage</a> | <a class="xrefp" href="#filesstat">Opened files</a> | <a class="xrefp" href="#mountcd">Mount/remount</a> | <a class="xrefp" href="#mountsmb">Mount SMB</a> | <a class="xrefp" href="#mountimg">Mount image</a> | <a class="xrefp" href="#burniso">Burn ISO</a> | <a class="xrefp" href="#createimg">Create image</a> | <a class="xrefp" href="#creatememdisk">Memory disk</a> | <a class="xrefp" href="#diskperf">Disk performance</a></p>
<h2 id="permissions">Permissions</h2>
Change permission and ownership with <code>chmod</code> and <code>chown</code>. The default umask can be changed for all users in /etc/profile for Linux or /etc/login.conf for FreeBSD. The default umask is usually 022. The umask is subtracted from 777, thus umask 022 results in a permission 0f 755.
<pre>1 --x execute                        <span class="cmt"># Mode 764 = exec/read/write | read/write | read</span>
2 -w- write                          <span class="cmt"># For:       |--  Owner  --|   |- Group-|   |Oth|</span>
4 r-- read
  ugo=a                              <span class="cmt">u=user, g=group, o=others, a=everyone</span>
</pre>
<pre># chmod [OPTION] MODE[,MODE] FILE    <span class="cmt"># MODE is of the form [ugoa]*([-+=]([rwxXst]))</span>
# chmod 640 /var/log/maillog         <span class="cmt"># Restrict the log -rw-r-----</span>
# chmod u=rw,g=r,o= /var/log/maillog <span class="cmt"># Same as above</span>
# chmod -R o-r /home/*               <span class="cmt"># Recursive remove other readable for all users</span>
# chmod u+s /path/to/prog            <span class="cmt"># Set SUID bit on executable (know what you do!)</span>
# find / -perm -u+s -print           <span class="cmt"># Find all programs with the SUID bit</span>
# chown user:group /path/to/file     <span class="cmt"># Change the user and group ownership of a file</span>
# chgrp group /path/to/file          <span class="cmt"># Change the group ownership of a file</span>
# chmod 640 `find ./ -type f -print` <span class="cmt"># Change permissions to 640 for all files</span>
# chmod 751 `find ./ -type d -print` <span class="cmt"># Change permissions to 751 for all directories</span>
</pre>
<h2 id="diskinfo">Disk information</h2>
<pre># diskinfo -v /dev/ad2               <span class="cmt"># information about disk (sector/size) FreeBSD</span>
# hdparm -I /dev/sda                 <span class="cmt"># information about the IDE/ATA disk (Linux)</span>
# fdisk /dev/ad2                     <span class="cmt"># Display and manipulate the partition table</span>
# smartctl -a /dev/ad2               <span class="cmt"># Display the disk SMART info</span>
</pre>
<h2 id="fsboot">Boot</h2>
<h3>FreeBSD</h3>
To boot an old kernel if the new kernel doesn't boot, stop the boot at during the count down.
<pre># unload
# load kernel.old
# boot
</pre>

<h2 id="mountpoints">System mount points/Disk usage</h2>
<pre># mount | column -t                  <span class="cmt"># Show mounted file-systems on the system</span>
# df                                 <span class="cmt"># display free disk space and mounted devices</span>
# cat /proc/partitions               <span class="cmt"># Show all registered partitions (Linux)</span>
</pre>

<h3 id="diskusage">Disk usage</h3>
<pre># du -sh *                           <span class="cmt"># Directory sizes as listing</span>
# du -csh                            <span class="cmt"># Total directory size of the current directory</span>
# du -ks * | sort -n -r              <span class="cmt"># Sort everything by size in kilobytes</span>
# ls -lSr                            <span class="cmt"># Show files, biggest last</span>
</pre>

<h2 id="filesstat">Who has which files opened</h2>
This is useful to find out which file is blocking a partition which has to be unmounted and gives a typical error of:
<pre># umount /home/
umount: unmount of /home             <span class="cmt"># umount impossible because a file is locking home</span>
   failed: Device busy
</pre>
<h3>FreeBSD and most Unixes</h3>
<pre># fstat -f /home                     <span class="cmt"># for a mount point</span>
# fstat -p PID                       <span class="cmt"># for an application with PID</span>
# fstat -u user                      <span class="cmt"># for a user name</span>
</pre>

Find opened log file (or other opened files), say for Xorg:
<pre># ps ax | grep Xorg | awk '{print $1}'
1252
# fstat -p 1252
USER     CMD          PID   FD MOUNT      INUM MODE         SZ|DV R/W
root     Xorg        1252 root /             2 drwxr-xr-x     512  r
root     Xorg        1252 text /usr     216016 -rws--x--x  1679848 r
root     Xorg        1252    0 /var     212042 -rw-r--r--   56987  w
</pre>
The file with inum 212042 is the only file in /var:
<pre># find -x /var -inum 212042
/var/log/Xorg.0.log
</pre>

<h3>Linux</h3>
Find opened files on a mount point with <code>fuser</code> or <code>lsof</code>:
<pre># fuser -m /home                     <span class="cmt"># List processes accessing /home</span>
# lsof /home
COMMAND   PID    USER   FD   TYPE DEVICE    SIZE     NODE NAME
tcsh    29029 eedcoba  cwd    DIR   0,18   12288  1048587 /home/eedcoba (guam:/home)
lsof    29140 eedcoba  cwd    DIR   0,18   12288  1048587 /home/eedcoba (guam:/home)
</pre>
About an application:
<pre>ps ax | grep Xorg | awk '{print $1}'
3324
# lsof -p 3324
COMMAND   PID    USER   FD   TYPE DEVICE    SIZE    NODE NAME
Xorg    3324 root    0w   REG        8,6   56296      12492 /var/log/Xorg.0.log
</pre>

About a single file:
<pre># lsof /var/log/Xorg.0.log
COMMAND  PID USER   FD   TYPE DEVICE  SIZE  NODE NAME
Xorg    3324 root    0w   REG    8,6 56296 12492 /var/log/Xorg.0.log
</pre>

<h2 id="mountcd">Mount/remount a file system</h2>
For example the cdrom. If listed in /etc/fstab:
<pre># mount /cdrom</pre>
Or find the device in /dev/ or with dmesg
<h3>FreeBSD</h3>
<pre># mount -v -t cd9660 /dev/cd0c /mnt  <span class="cmt"># cdrom</span>
# mount_cd9660 /dev/wcd0c /cdrom     <span class="cmt"># other method</span>
# mount -v -t msdos /dev/fd0c /mnt   <span class="cmt"># floppy</span>
</pre>
Entry in /etc/fstab:
<pre># Device                Mountpoint      FStype  Options         Dump    Pass#
/dev/acd0               /cdrom          cd9660  ro,noauto       0       0
</pre>
To let users do it:
<pre># sysctl vfs.usermount=1  <span class="cmt"># Or insert the line "vfs.usermount=1" in /etc/sysctl.conf</span>
</pre>

<h3>Linux</h3>
<pre># mount -t auto /dev/cdrom /mnt/cdrom   <span class="cmt"># typical cdrom mount command</span>
# mount /dev/hdc -t iso9660 -r /cdrom   <span class="cmt"># typical IDE</span>
# mount /dev/scd0 -t iso9660 -r /cdrom  <span class="cmt"># typical SCSI cdrom</span>
# mount /dev/sdc0 -t ntfs-3g /windows   <span class="cmt"># typical SCSI</span>
</pre>
Entry in /etc/fstab:
<pre>/dev/cdrom   /media/cdrom  subfs noauto,fs=cdfss,ro,procuid,nosuid,nodev,exec 0 0</pre>
<h4>Mount a FreeBSD partition with Linux</h4>
Find the partition number containing with fdisk, this is usually the root partition, but it could be an other BSD slice too. If the FreeBSD has many slices, they are the one not listed in the fdisk table, but visible in /dev/sda* or /dev/hda*.
<pre># fdisk /dev/sda                     <span class="cmt"># Find the FreeBSD partition</span>
/dev/sda3   *        5357        7905    20474842+  a5  FreeBSD
# mount -t ufs -o ufstype=ufs2,ro /dev/sda3 /mnt
/dev/sda10 = /tmp; /dev/sda11 /usr   <span class="cmt"># The other slices</span>
</pre>
<h3 id="remount">Remount</h3>
Remount a device without unmounting it. Necessary for fsck for example
<pre># mount -o remount,ro /              <span class="cmt"># Linux</span>
# mount -o ro /                      <span class="cmt"># FreeBSD</span>
</pre>
Copy the raw data from a cdrom into an iso image:
<pre># dd if=/dev/cd0c of=file.iso</pre>

<h2 id="addswap">Add swap on-the-fly</h2>
Suppose you need more swap (right now), say a 2GB file /swap2gb (Linux only).
<pre># dd if=/dev/zero of=/swap2gb bs=1024k count=2000
# mkswap /swap2gb                    <span class="cmt"># create the swap area</span>
# swapon /swap2gb                    <span class="cmt"># activate the swap. It now in use</span>
# swapoff /swap2gb                   <span class="cmt"># when done deactivate the swap</span>
# rm /swap2gb
</pre>

<h2 id="mountsmb">Mount an SMB share</h2>
Suppose we want to access the SMB share myshare on the computer smbserver, the address as typed on a Windows PC is \\smbserver\myshare\. We mount on /mnt/smbshare. Warning&gt; cifs wants an IP or DNS name, not a Windows name.
<h3>Linux</h3>
<pre># smbclient -U user -I 192.168.16.229 -L //smbshare/    <span class="cmt"># List the shares</span>
# mount -t smbfs -o username=winuser //smbserver/myshare /mnt/smbshare
# mount -t cifs -o username=winuser,password=winpwd //192.168.16.229/myshare /mnt/share
</pre>
Additionally with the package mount.cifs it is possible to store the credentials in a file, for example <code>/home/user/.smb</code>:
<pre>username=winuser
password=winpwd
</pre>
And mount as follow:
<pre># mount -t cifs -o credentials=/home/user/.smb //192.168.16.229/myshare /mnt/smbshare</pre>

<h3>FreeBSD</h3>
Use -I to give the IP (or DNS name); smbserver is the Windows name.
<pre># smbutil view -I 192.168.16.229 //winuser@smbserver    <span class="cmt"># List the shares</span>
# mount_smbfs -I 192.168.16.229 //winuser@smbserver/myshare /mnt/smbshare
</pre>

<h2 id="mountimg">Mount an image</h2>
<h3>Linux loop-back</h3>
<pre># mount -t iso9660 -o loop file.iso /mnt                <span class="cmt"># Mount a CD image</span>
# mount -t ext3 -o loop file.img /mnt                   <span class="cmt"># Mount an image with ext3 fs</span>
</pre>

<h3>FreeBSD</h3>
With memory device (do # kldload md.ko if necessary):
<pre># mdconfig -a -t vnode -f file.iso -u 0
# mount -t cd9660 /dev/md0 /mnt
# umount /mnt; mdconfig -d -u 0                         <span class="cmt"># Cleanup the md device</span>
</pre>
Or with virtual node:
<pre># vnconfig /dev/vn0c file.iso; mount -t cd9660 /dev/vn0c /mnt
# umount /mnt; vnconfig -u /dev/vn0c                    <span class="cmt"># Cleanup the vn device</span>
</pre>

<h3>Solaris and FreeBSD</h3>
with loop-back file interface or lofi:
<pre># lofiadm -a file.iso
# mount -F hsfs -o ro /dev/lofi/1 /mnt
# umount /mnt; lofiadm -d /dev/lofi/1                   <span class="cmt"># Cleanup the lofi device</span>
</pre>
<h2 id="burniso">Create and burn an ISO image</h2>
This will copy the cd or DVD sector for sector. Without <code>conv=notrunc</code>, the image will be smaller if there is less content on the cd. See below and the <a class="xref" href="#dd">dd examples</a>.
<pre># dd if=/dev/hdc of=/tmp/mycd.iso bs=2048 conv=notrunc</pre>
Use mkisofs to create a CD/DVD image from files in a directory. To overcome the file names restrictions: -r enables the Rock Ridge extensions common to UNIX systems, -J enables Joliet extensions used by Microsoft systems. -L allows ISO9660 filenames to begin with a period.
<pre># mkisofs -J -L -r -V TITLE -o imagefile.iso /path/to/dir</pre>
On FreeBSD, mkisofs is found in the ports in sysutils/cdrtools.
<h3>Burn a CD/DVD ISO image</h3>
<h4>FreeBSD</h4>
FreeBSD does not enable DMA on ATAPI drives by default. DMA is enabled with the sysctl command and the arguments below, or with /boot/loader.conf with the following entries:
<pre>hw.ata.ata_dma="1"
hw.ata.atapi_dma="1"
</pre>
Use <code>burncd</code> with an ATAPI device (<code>burncd</code> is part of the base system) and <code>cdrecord</code> (in sysutils/cdrtools) with a SCSI drive.
<pre># burncd -f /dev/acd0 data imagefile.iso fixate      <span class="cmt"># For ATAPI drive</span>
# cdrecord -scanbus                  <span class="cmt"># To find the burner device (like 1,0,0)</span>
# cdrecord dev=1,0,0 imagefile.iso
</pre>
<h4>Linux</h4>
Also use <code>cdrecord</code> with Linux as described above. Additionally it is possible to use the native ATAPI interface which is found with:
<pre># cdrecord dev=ATAPI -scanbus</pre>
And burn the CD/DVD as above.
<h4>dvd+rw-tools</h4>
The <a href="http://fy.chalmers.se/~appro/linux/DVD+RW/">dvd+rw-tools</a> package (FreeBSD: ports/sysutils/dvd+rw-tools) can do it all and includes <code>growisofs</code> to burn CDs or DVDs. The examples refere to the dvd device as <code>/dev/dvd</code> which could be a symlink to <code>/dev/scd0</code> (typical scsi on Linux) or <code>/dev/cd0</code> (typical FreeBSD) or <code>/dev/rcd0c</code> (typical NetBSD/OpenBSD character SCSI) or <code>/dev/rdsk/c0t1d0s2</code> (Solaris example of a character SCSI/ATAPI CD-ROM device). There is a nice documentation with examples on the <a href="http://www.freebsd.org/handbook/creating-dvds.html">FreeBSD handbook chapter 18.7</a><span class="fn">http://www.freebsd.org/handbook/creating-dvds.html</span>.
<pre>                       <span class="cmt"># -dvd-compat closes the disk</span>
# growisofs -dvd-compat -Z /dev/dvd=imagefile.iso     <span class="cmt"># Burn existing iso image</span>
# growisofs -dvd-compat -Z /dev/dvd -J -R /p/to/data  <span class="cmt"># Burn directly</span>
</pre>

<h3>Convert a Nero .nrg file to .iso</h3>
Nero simply adds a 300Kb header to a normal iso image. This can be trimmed with dd.
<pre># dd bs=1k if=imagefile.nrg of=imagefile.iso skip=300</pre>
<h3>Convert a bin/cue image to .iso</h3>
The little <a href="http://freshmeat.net/projects/bchunk/"><code>bchunk</code> program</a><span class="fn">http://freshmeat.net/projects/bchunk/</span> can do this. It is in the FreeBSD ports in sysutils/bchunk.
<pre># bchunk imagefile.bin imagefile.cue imagefile.iso
</pre>

<h2 id="createimg">Create a file based image</h2>
For example a partition of 1GB using the file /usr/vdisk.img. Here we use the vnode 0, but it could also be 1.
<h3>FreeBSD</h3>
<pre># dd if=/dev/random of=/usr/vdisk.img bs=1K count=1M
# mdconfig -a -t vnode -f /usr/vdisk.img -u 0         <span class="cmt"># Creates device /dev/md1</span>
# bsdlabel -w /dev/md0
# newfs /dev/md0c
# mount /dev/md0c /mnt
# umount /mnt; mdconfig -d -u 0; rm /usr/vdisk.img    <span class="cmt"># Cleanup the md device</span>
</pre>
The file based image can be automatically mounted during boot with an entry in /etc/rc.conf and /etc/fstab. Test your setup with <code># /etc/rc.d/mdconfig start</code> (first delete the md0 device with <code># mdconfig -d -u 0</code>).<br/>
Note however that this automatic setup will only work if the file image is NOT on the root partition. The reason is that the /etc/rc.d/mdconfig script is executed very early buring boot and the root partition is still read-only. Images located outside the root partition will be mounted later with the script /etc/rc.d/mdconfig2.<br/>
/boot/loader.conf:
<pre>md_load="YES"</pre>
/etc/rc.conf:
<pre># mdconfig_md0="-t vnode -f /usr/vdisk.img"          <span class="cmt"># /usr is not on the root partition</span></pre>
/etc/fstab: (The 0 0 at the end is important, it tell fsck to ignore this device, as is does not exist yet)
<pre>/dev/md0                /usr/vdisk      ufs     rw              0       0</pre>
It is also possible to increase the size of the image afterward, say for example 300 MB larger.
<pre># umount /mnt; mdconfig -d -u 0
# dd if=/dev/zero bs=1m count=300 &gt;&gt; /usr/vdisk.img
# mdconfig -a -t vnode -f /usr/vdisk.img -u 0
# growfs /dev/md0
# mount /dev/md0c /mnt                                <span class="cmt"># File partition is now 300 MB larger</span>
</pre>

<h3>Linux</h3>

<pre># dd if=/dev/zero of=/usr/vdisk.img bs=1024k count=1024
# mkfs.ext3 /usr/vdisk.img
# mount -o loop /usr/vdisk.img /mnt
# umount /mnt; rm /usr/vdisk.img                      <span class="cmt"># Cleanup</span>
</pre>
<h3 id="losetup">Linux with losetup</h3>
<code>/dev/zero</code> is much faster than <code>urandom</code>, but less secure for encryption.
<pre># dd if=/dev/urandom of=/usr/vdisk.img bs=1024k count=1024
# losetup /dev/loop0 /usr/vdisk.img                   <span class="cmt"># Creates and associates /dev/loop0</span>
# mkfs.ext3 /dev/loop0
# mount /dev/loop0 /mnt
# losetup -a                                          <span class="cmt"># Check used loops</span>
# umount /mnt
# losetup -d /dev/loop0                               <span class="cmt"># Detach</span>
# rm /usr/vdisk.img
</pre>

<h2 id="creatememdisk">Create a memory file system</h2>
A memory based file system is very fast for heavy IO application. How to create a 64 MB partition mounted on /memdisk:
<h3>FreeBSD</h3>
<pre># mount_mfs -o rw -s 64M md /memdisk
# umount /memdisk; mdconfig -d -u 0                   <span class="cmt"># Cleanup the md device</span>
md     /memdisk     mfs     rw,-s64M    0   0         <span class="cmt"># /etc/fstab entry</span>
</pre>
<h3>Linux</h3>
<pre># mount -t tmpfs -osize=64m tmpfs /memdisk
</pre>

<h2 id="diskperf">Disk performance</h2>
Read and write a 1 GB file on partition ad4s3c (/home)
<pre># time dd if=/dev/ad4s3c of=/dev/null bs=1024k count=1000
# time dd if=/dev/zero bs=1024k count=1000 of=/home/1Gb.file
# hdparm -tT /dev/hda      <span class="cmt"># Linux only</span>
</pre>
</div>

<div id="network"><h1><a>Network</a></h1>
<p class="xrefp"><a class="xrefp" href="#routing">Routing</a> | <a class="xrefp" href="#secondip">Additional IP</a> | <a class="xrefp" href="#changemac">Change MAC</a> | <a class="xrefp" href="#ports">Ports</a> | <a class="xrefp" href="#firewall">Firewall</a> | <a class="xrefp" href="#ipforward">IP Forward</a> | <a class="xrefp" href="#nat">NAT</a> | <a class="xrefp" href="#dns">DNS</a> | <a class="xrefp" href="#dhcp">DHCP</a> | <a class="xrefp" href="#traffic">Traffic</a> | <a class="xrefp" href="#trafficctrl">QoS</a> | <a class="xrefp" href="#nis">NIS</a></p>
<h2 id="netdebug">Debugging (See also <a class="xref" href="#traffic">Traffic analysis)</a></h2>
<h3>Linux</h3>
<pre># ethtool eth0              <span class="cmt"># Show the ethernet status (replaces mii-diag)</span>
# ethtool -s eth0 speed 100 duplex full <span class="cmt"># Force 100Mbit Full duplex</span>
# ethtool -s eth0 autoneg off <span class="cmt"># Disable auto negotiation</span>
# ethtool -p eth1           <span class="cmt"># Blink the ethernet led - very useful when supported</span>
# ip link show              <span class="cmt"># Display all interfaces on Linux (similar to ifconfig)</span>
# ip link set eth0 up       <span class="cmt"># Bring device up (or down). Same as "ifconfig eth0 up"</span>
# ip addr show              <span class="cmt"># Display all IP addresses on Linux (similar to ifconfig)</span>
# ip neigh show             <span class="cmt"># Similar to arp -a</span>
</pre>
<h3>Other OSes</h3>
<pre># ifconfig fxp0             <span class="cmt"># Check the "media" field on FreeBSD</span>
# arp -a                    <span class="cmt"># Check the router (or host) ARP entry (all OS)</span>
# ping cb.vu                <span class="cmt"># The first thing to try...</span>
# traceroute cb.vu          <span class="cmt"># Print the route path to destination</span>
# ifconfig fxp0 media 100baseTX mediaopt full-duplex <span class="cmt"># 100Mbit full duplex (FreeBSD)</span>
# netstat -s                <span class="cmt"># System-wide statistics for each network protocol</span>
</pre>
Additional commands which are not always installed per default but easy to find:
<pre># arping 192.168.16.254     <span class="cmt"># Ping on ethernet layer</span>
# tcptraceroute -f 5 cb.vu  <span class="cmt"># uses tcp instead of icmp to trace throught firewalls</span>
</pre>

<h2 id="routing">Routing</h2>
<h3>Print routing table</h3>
<pre># route -n                  <span class="cmt"># Linux or use "ip route"</span>
# netstat -rn               <span class="cmt"># Linux, BSD and UNIX</span>
# route print               <span class="cmt"># Windows</span>
</pre>
<h3 id="addroute">Add and delete a route</h3>
<h4>FreeBSD</h4>
<pre># route add 212.117.0.0/16 192.168.1.1
# route delete 212.117.0.0/16
# route add default 192.168.1.1
</pre>
Add the route permanently in /etc/rc.conf
<pre>static_routes="myroute"
route_myroute="-net 212.117.0.0/16 192.168.1.1"
</pre>
<h4>Linux</h4>
<pre># route add -net 192.168.20.0 netmask 255.255.255.0 gw 192.168.16.254
# ip route add 192.168.20.0/24 via 192.168.16.254       <span class="cmt"># same as above with ip route</span>
# route add -net 192.168.20.0 netmask 255.255.255.0 dev eth0
# route add default gw 192.168.51.254
# ip route add default via 192.168.51.254 dev eth0      <span class="cmt"># same as above with ip route</span>
# route delete -net 192.168.20.0 netmask 255.255.255.0
</pre>
<h4>Solaris</h4>
<pre># route add -net 192.168.20.0 -netmask 255.255.255.0 192.168.16.254
# route add default 192.168.51.254 1                    <span class="cmt"># 1 = hops to the next gateway</span>
# route change default 192.168.50.254 1
</pre>
Permanent entries are set in entry in <code>/etc/defaultrouter</code>.
<h4>Windows</h4>
<pre># Route add 192.168.50.0 mask 255.255.255.0 192.168.51.253
# Route add 0.0.0.0 mask 0.0.0.0 192.168.51.254</pre>
Use add -p to make the route persistent.

<h2 id="secondip">Configure additional IP addresses</h2>
<h3>Linux</h3>
<pre># ifconfig eth0 192.168.50.254 netmask 255.255.255.0       <span class="cmt"># First IP</span>
# ifconfig eth0:0 192.168.51.254 netmask 255.255.255.0     <span class="cmt"># Second IP</span>
# ip addr add 192.168.50.254/24 dev eth0                   <span class="cmt"># Equivalent ip commands</span>
# ip addr add 192.168.51.254/24 dev eth0 label eth0:1
</pre>
<h3>FreeBSD</h3>
<pre># ifconfig fxp0 inet 192.168.50.254/24                     <span class="cmt"># First IP</span>
# ifconfig fxp0 alias 192.168.51.254 netmask 255.255.255.0 <span class="cmt"># Second IP</span>
</pre>Permanent entries in /etc/rc.conf                   
<pre>ifconfig_fxp0="inet 192.168.50.254  netmask 255.255.255.0"
ifconfig_fxp0_alias0="192.168.51.254 netmask 255.255.255.0"
</pre>
<h3>Solaris</h3>
Check the settings with <code>ifconfig -a</code>
<pre># ifconfig hme0 plumb                                      <span class="cmt"># Enable the network card</span>
# ifconfig hme0 192.168.50.254 netmask 255.255.255.0 up    <span class="cmt"># First IP</span>
# ifconfig hme0:1 192.168.51.254 netmask 255.255.255.0 up  <span class="cmt"># Second IP</span>
</pre>

<h2 id="changemac">Change MAC address</h2>
Normally you have to bring the interface down before the change. Don't tell me why you want to change the MAC address...
<pre># ifconfig eth0 down
# ifconfig eth0 hw ether 00:01:02:03:04:05      <span class="cmt"># Linux</span>
# ifconfig fxp0 link 00:01:02:03:04:05          <span class="cmt"># FreeBSD</span>
# ifconfig hme0 ether 00:01:02:03:04:05         <span class="cmt"># Solaris</span>
# sudo ifconfig en0 ether 00:01:02:03:04:05     <span class="cmt"># Mac OS X Tiger</span>
# sudo ifconfig en0 lladdr 00:01:02:03:04:05    <span class="cmt"># Mac OS X Leopard</span>
</pre>
Many tools exist for Windows. For example <a href="http://ntsecurity.nu/toolbox/etherchange/">etherchange</a><span class="fn">http://ntsecurity.nu/toolbox/etherchange</span>. Or look for "Mac Makeup", "smac".

<h2 id="ports">Ports in use</h2>
Listening open ports:
<pre># netstat -an | grep LISTEN
# lsof -i                  <span class="cmt"># Linux list all Internet connections</span>
# socklist                 <span class="cmt"># Linux display list of open sockets</span>
# sockstat -4              <span class="cmt"># FreeBSD application listing</span>
# netstat -anp --udp --tcp | grep LISTEN        <span class="cmt"># Linux</span>
# netstat -tup             <span class="cmt"># List active connections to/from system (Linux)</span>
# netstat -tupl            <span class="cmt"># List listening ports from system (Linux)</span>
# netstat -ano             <span class="cmt"># Windows</span>
</pre>

<h2 id="firewall">Firewall</h2>
Check if a firewall is running (typical configuration only):
<h3>Linux</h3>
<pre># iptables -L -n -v                  <span class="cmt"># For status</span>
Open the iptables firewall
# iptables -P INPUT       ACCEPT     <span class="cmt"># Open everything</span>
# iptables -P FORWARD     ACCEPT
# iptables -P OUTPUT      ACCEPT
# iptables -Z                        <span class="cmt"># Zero the packet and byte counters in all chains</span>
# iptables -F                        <span class="cmt"># Flush all chains</span>
# iptables -X                        <span class="cmt"># Delete all chains</span>
</pre>
<h3>FreeBSD</h3>
<pre># ipfw show                          <span class="cmt"># For status</span>
# ipfw list 65535 <span class="cmt"># if answer is "65535 deny ip from any to any" the fw is disabled</span>
# sysctl net.inet.ip.fw.enable=0     <span class="cmt"># Disable</span>
# sysctl net.inet.ip.fw.enable=1     <span class="cmt"># Enable</span>
</pre>
<h2 id="ipforward">IP Forward for routing</h2>
<h3>Linux</h3>
Check and then enable IP forward with:
<pre># cat /proc/sys/net/ipv4/ip_forward  <span class="cmt"># Check IP forward 0=off, 1=on</span>
# echo 1 &gt; /proc/sys/net/ipv4/ip_forward
</pre>
or edit /etc/sysctl.conf with:
<pre>net.ipv4.ip_forward = 1</pre>

<h3>FreeBSD</h3>
Check and enable with:
<pre># sysctl net.inet.ip.forwarding      <span class="cmt"># Check IP forward 0=off, 1=on</span>
# sysctl net.inet.ip.forwarding=1
# sysctl net.inet.ip.fastforwarding=1	<span class="cmt"># For dedicated router or firewall</span>
Permanent with entry in /etc/rc.conf:
gateway_enable="YES"                 <span class="cmt"># Set to YES if this host will be a gateway.</span>
</pre>

<h3>Solaris</h3>
<pre># ndd -set /dev/ip ip_forwarding 1   <span class="cmt"># Set IP forward 0=off, 1=on</span>
</pre>

<h2 id="nat">NAT Network Address Translation</h2>
<h3>Linux</h3>
<pre># iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE	<span class="cmt"># to activate NAT</span>
# iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 20022 -j DNAT \
--to 192.168.16.44:22           <span class="cmt"># Port forward 20022 to internal IP port ssh</span>
# iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 993:995 -j DNAT \
--to 192.168.16.254:993:995     <span class="cmt"># Port forward of range 993-995</span>
# ip route flush cache
# iptables -L -t nat            <span class="cmt"># Check NAT status</span>
</pre>
Delete the port forward with -D instead of -A.

<h3>FreeBSD</h3>
<pre># natd -s -m -u -dynamic -f /etc/natd.conf -n fxp0
Or edit /etc/rc.conf with:
firewall_enable="YES"           <span class="cmt"># Set to YES to enable firewall functionality</span>
firewall_type="open"            <span class="cmt"># Firewall type (see /etc/rc.firewall)</span>
natd_enable="YES"               <span class="cmt"># Enable natd (if firewall_enable == YES).</span>
natd_interface="tun0"           <span class="cmt"># Public interface or IP address to use.</span>
natd_flags="-s -m -u -dynamic -f /etc/natd.conf"
</pre>
Port forward with:
<pre># cat /etc/natd.conf 
same_ports yes
use_sockets yes
unregistered_only
# redirect_port tcp insideIP:2300-2399 3300-3399  <span class="cmt"># port range</span>
redirect_port udp 192.168.51.103:7777 7777
</pre>

<h2 id="dns">DNS</h2>
On Unix the DNS entries are valid for all interfaces and are stored in /etc/resolv.conf. The domain to which the host belongs is also stored in this file. A minimal configuration is:
<pre>nameserver 78.31.70.238
search sleepyowl.net intern.lab
domain sleepyowl.net
</pre>
Check the system domain name with:
<pre># hostname -d                        <span class="cmt"># Same as dnsdomainname</span></pre>
<h3>Windows</h3>
On Windows the DNS are configured per interface. To display the configured DNS and to flush the DNS cache use:
<pre># ipconfig /?                        <span class="cmt"># Display help</span>
# ipconfig /all                      <span class="cmt"># See all information including DNS</span>
# ipconfig /flushdns                 <span class="cmt"># Flush the DNS cache</span>
</pre>

<h3>Forward queries</h3>
Dig is you friend to test the DNS settings. For example the public DNS server <code>213.133.105.2 ns.second-ns.de</code> can be used for testing. See from which server the client receives the answer (simplified answer).
<pre># dig sleepyowl.net
sleepyowl.net.          600     IN      A       78.31.70.238
;; SERVER: 192.168.51.254#53(192.168.51.254)
</pre>
The router 192.168.51.254 answered and the response is the A entry. Any entry can be queried and the DNS server can be selected with @:
<pre># dig MX google.com
# dig @127.0.0.1 NS sun.com          <span class="cmt"># To test the local server</span>
# dig @204.97.212.10 NS MX heise.de  <span class="cmt"># Query an external server</span>
# dig AXFR @ns1.xname.org cb.vu      <span class="cmt"># Get the full zone (zone transfer)</span>
</pre>
The program host is also powerful.
<pre># host -t MX cb.vu                   <span class="cmt"># Get the mail MX entry</span>
# host -t NS -T sun.com              <span class="cmt"># Get the NS record over a TCP connection</span>
# host -a sleepyowl.net              <span class="cmt"># Get everything</span>
</pre>

<h3>Reverse queries</h3>
Find the name belonging to an IP address (in-addr.arpa.). This can be done with <code>dig</code>, <code>host</code> and <code>nslookup</code>:
<pre># dig -x 78.31.70.238
# host 78.31.70.238
# nslookup 78.31.70.238
</pre>

<h3>/etc/hosts</h3>
Single hosts can be configured in the file /etc/hosts instead of running <code>named</code> locally to resolve the hostname queries. The format is simple, for example:
<pre>78.31.70.238   sleepyowl.net   sleepyowl</pre>
The priority between hosts and a dns query, that is the name resolution order, can be configured in <code>/etc/nsswitch.conf</code> AND /etc/host.conf. The file also exists on Windows, it is usually in:
<pre>C:\WINDOWS\SYSTEM32\DRIVERS\ETC</pre>

<h2 id="dhcp">DHCP</h2>
<h3>Linux</h3>
Some distributions (SuSE) use dhcpcd as client. The default interface is eth0.
<pre># dhcpcd -n eth0           <span class="cmt"># Trigger a renew (does not always work)</span>
# dhcpcd -k eth0           <span class="cmt"># release and shutdown</span>
</pre>
The lease with the full information is stored in:
<pre>/var/lib/dhcpcd/dhcpcd-eth0.info</pre>

<h3>FreeBSD</h3>
FreeBSD (and Debian) uses dhclient. To configure an interface (for example bge0) run:
<pre># dhclient bge0</pre>
The lease with the full information is stored in:
<pre>/var/db/dhclient.leases.bge0</pre>
Use <pre>/etc/dhclient.conf</pre> to prepend options or force different options:
<pre># cat /etc/dhclient.conf
interface "rl0" {
    prepend domain-name-servers 127.0.0.1;
    default domain-name "sleepyowl.net";
    supersede domain-name "sleepyowl.net";
}
</pre>

<h3>Windows</h3>
The dhcp lease can be renewed with <code>ipconfig</code>:
<pre># ipconfig /renew          <span class="cmt"># renew all adapters</span>
# ipconfig /renew LAN      <span class="cmt"># renew the adapter named "LAN"</span>
# ipconfig /release WLAN   <span class="cmt"># release the adapter named "WLAN"</span>
</pre>
Yes it is a good idea to rename you adapter with simple names!


<h2 id="traffic">Traffic analysis</h2>
<a href="http://people.suug.ch/~tgr/bmon/">Bmon</a><span class="fn">http://people.suug.ch/~tgr/bmon/</span> is a small console bandwidth monitor and can display the flow on different interfaces. 
<h3>Sniff with tcpdump</h3>
<pre># tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.168.16.54\)
# tcpdump -l &gt; dump &amp;&amp; tail -f dump               <span class="cmt"># Buffered output</span>
# tcpdump -i rl0 -w traffic.rl0                   <span class="cmt"># Write traffic in binary file</span>
# tcpdump -r traffic.rl0                          <span class="cmt"># Read from file (also for ethereal</span>
# tcpdump port 80                                 <span class="cmt"># The two classic commands</span>
# tcpdump host google.com
# tcpdump -i eth0 -X port \(110 or 143\)          <span class="cmt"># Check if pop or imap is secure</span>
# tcpdump -n -i eth0 icmp                         <span class="cmt"># Only catch pings</span>
# tcpdump -i eth0 -s 0 -A port 80 | grep GET      <span class="cmt"># -s 0 for full packet -A for ASCII</span>
</pre>
Additional important options:
<ul style="list-style-type: none;">
  <li><code>-A</code>     Print each packets in clear text (without header)</li>
  <li><code>-X</code>     Print packets in hex and ASCII</li>
  <li><code>-l</code>     Make stdout line buffered</li>
  <li><code>-D</code>     Print all interfaces available</li>
</ul>

On Windows use windump from <a rel="nofollow" href="http://www.winpcap.org/">www.winpcap.org</a>. Use windump -D to list the interfaces.
<h3>Scan with nmap</h3>
<a rel="nofollow" href="http://insecure.org/nmap/">Nmap</a><span class="fn">http://insecure.org/nmap/</span> is a port scanner with OS detection, it is usually installed on most distributions and is also available for Windows. If you don't scan your servers, hackers do it for you...
<pre># nmap cb.vu               <span class="cmt"># scans all reserved TCP ports on the host</span>
# nmap -sP 192.168.16.0/24 <span class="cmt"># Find out which IP are used and by which host on 0/24</span>
# nmap -sS -sV -O cb.vu    <span class="cmt"># Do a stealth SYN scan with version and OS detection</span>
PORT      STATE  SERVICE             VERSION
22/tcp    open   ssh                 OpenSSH 3.8.1p1 FreeBSD-20060930 (protocol 2.0)
25/tcp    open   smtp                Sendmail smtpd 8.13.6/8.13.6
80/tcp    open   http                Apache httpd 2.0.59 ((FreeBSD) DAV/2 PHP/4.
[...]
Running: FreeBSD 5.X
Uptime 33.120 days (since Fri Aug 31 11:41:04 2007)
</pre>
Other non standard but useful tools are <code>hping</code> (www.hping.org) an IP packet assembler/analyzer and <code>fping</code> (fping.sourceforge.net). fping can check multiple hosts in a round-robin fashion.

<h2 id="trafficctrl">Traffic control (QoS)</h2>
Traffic control manages the queuing, policing, scheduling, and other traffic parameters for a network. The following examples are simple practical uses of the Linux and FreeBSD capabilities to better use the available bandwidth.
<h3>Limit upload</h3>
DSL or cable modems have a long queue to improve the upload throughput. However filling the queue with a fast device (e.g. ethernet) will dramatically decrease the interactivity. It is therefore useful to limit the device upload rate to match the physical capacity of the modem, this should greatly improve the interactivity. Set to about 90% of the modem maximal (cable) speed.
<h4>Linux</h4>
For a 512 Kbit upload modem.
<pre># tc qdisc add dev eth0 root tbf rate 480kbit latency 50ms burst 1540
# tc -s qdisc ls dev eth0                         <span class="cmt"># Status</span>
# tc qdisc del dev eth0 root                      <span class="cmt"># Delete the queue</span>
# tc qdisc change dev eth0 root tbf rate 220kbit latency 50ms burst 1540
</pre>
<h4>FreeBSD</h4>
FreeBSD uses the <code>dummynet</code> traffic shaper which is configured with ipfw. Pipes are used to set limits the bandwidth in units of [K|M]{bit/s|Byte/s}, 0 means unlimited bandwidth. Using the same pipe number will reconfigure it. For example limit the upload bandwidth to 500 Kbit.
<pre>
# kldload dummynet                                <span class="cmt"># load the module if necessary</span>
# ipfw pipe 1 config bw 500Kbit/s                 <span class="cmt"># create a pipe with limited bandwidth</span>
# ipfw add pipe 1 ip from me to any               <span class="cmt"># divert the full upload into the pipe</span>
</pre>
<h3>Quality of service</h3>
<h4>Linux</h4>
Priority queuing with <code>tc</code> to optimize VoIP. See the full example on <a rel="nofollow" href="http://www.voip-info.org/wiki-QoS+Linux+with+HFS">voip-info.org</a> or <a rel="nofollow" href="http://www.howtoforge.com/voip_qos_traffic_shaping_iproute2_asterisk">www.howtoforge.com</a>. Suppose VoIP uses udp on ports 10000:11024 and device eth0 (could also be ppp0 or so). The following commands define the QoS to three queues and force the VoIP traffic to queue 1 with QoS <code>0x1e</code> (all bits set). The default traffic flows into queue 3 and QoS <i>Minimize-Delay</i> flows into queue 2.
<pre># tc qdisc add dev eth0 root handle 1: prio priomap 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 0
# tc qdisc add dev eth0 parent 1:1 handle 10: sfq
# tc qdisc add dev eth0 parent 1:2 handle 20: sfq
# tc qdisc add dev eth0 parent 1:3 handle 30: sfq
# tc filter add dev eth0 protocol ip parent 1: prio 1 u32 \
  match ip dport 10000 0x3C00 flowid 1:1          <span class="cmt"># use server port range</span>
  match ip dst 123.23.0.1 flowid 1:1              <span class="cmt"># or/and use server IP</span>
</pre>
Status and remove with
<pre># tc -s qdisc ls dev eth0                         <span class="cmt"># queue status</span>
# tc qdisc del dev eth0 root                      <span class="cmt"># delete all QoS</span>
</pre>
<h4>Calculate port range and mask</h4>
The tc filter defines the port range with port and mask which you have to calculate. Find the 2^N <i>ending</i> of the port range, deduce the range and convert to HEX. This is your mask. Example for 10000 -&gt; 11024, the range is 1024.
<pre># 2^13 (8192) &lt; 10000 &lt; 2^14 (16384)              <span class="cmt"># ending is 2^14 = 16384</span>
# echo "obase=16;(2^14)-1024" | bc                <span class="cmt"># mask is 0x3C00</span>
</pre>

<h4>FreeBSD</h4>
The max link bandwidth is 500Kbit/s and we define 3 queues with priority 100:10:1 for VoIP:ssh:all the rest.
<pre># ipfw pipe 1 config bw 500Kbit/s 
# ipfw queue 1 config pipe 1 weight 100
# ipfw queue 2 config pipe 1 weight 10
# ipfw queue 3 config pipe 1 weight 1
# ipfw add 10 queue 1 proto udp dst-port 10000-11024
# ipfw add 11 queue 1 proto udp dst-ip 123.23.0.1 <span class="cmt"># or/and use server IP</span>
# ipfw add 20 queue 2 dsp-port ssh
# ipfw add 30 queue 3 from me to any              <span class="cmt"># all the rest</span>
</pre>
Status and remove with
<pre># ipfw list                                       <span class="cmt"># rules status</span>
# ipfw pipe list                                  <span class="cmt"># pipe status</span>
# ipfw flush                                      <span class="cmt"># deletes all rules but default</span>
</pre>
<h2 id="nis">NIS Debugging</h2>
Some commands which should work on a well configured NIS client:
<pre># ypwhich                  <span class="cmt"># get the connected NIS server name</span>
# domainname               <span class="cmt"># The NIS domain name as configured</span>
# ypcat group              <span class="cmt"># should display the group from the NIS server</span>
# cd /var/yp &amp;&amp; make       <span class="cmt"># Rebuild the yp database</span>
</pre>
Is ypbind running?
<pre># ps auxww | grep ypbind
/usr/sbin/ypbind -s -m -S servername1,servername2	<span class="cmt"># FreeBSD</span>
/usr/sbin/ypbind           <span class="cmt"># Linux</span>
# yppoll passwd.byname
Map passwd.byname has order number 1190635041. Mon Sep 24 13:57:21 2007
The master server is servername.domain.net.
</pre>
<h3>Linux</h3>
<pre># cat /etc/yp.conf
ypserver servername
domain domain.net broadcast
</pre>
</div>

<div id="ssh"><h1><a>SSH SCP</a></h1>
<p class="xrefp"><a class="xrefp" href="#publickey">Public key</a> | <a class="xrefp" href="#sshfingerprint">Fingerprint</a> | <a class="xrefp" href="#scp">SCP</a> | <a class="xrefp" href="#sshtunnel">Tunneling</a></p>
<h2 id="publickey">Public key authentication</h2>
Connect to a host without password using public key authentication. The idea is to append your public key to the authorized_keys2 file on the remote host. For this example let's <b>connect <i>host-client</i> to <i>host-server</i></b>, the key is generated on the client.
<ul>
  <li>Use ssh-keygen to generate a key pair. <code>~/.ssh/id_dsa</code> is the private key, <code>~/.ssh/id_dsa.pub</code> is the public key.</li>
  <li>Copy only the public key to the server and append it to the file <code>~/.ssh/authorized_keys2</code> on your home on the server.</li>
</ul>
<pre># ssh-keygen -t dsa -N ''
# cat ~/.ssh/id_dsa.pub | ssh you@host-server "cat - &gt;&gt; ~/.ssh/authorized_keys2"
</pre>

<h3>Using the Windows client from ssh.com</h3>
The non commercial version of the ssh.com client can be downloaded the main ftp site: <a rel="nofollow" href="http://ftp.ssh.com/pub/ssh/">ftp.ssh.com/pub/ssh/</a>. Keys generated by the ssh.com client need to be converted for the OpenSSH server. This can be done with the ssh-keygen command.
<ul>
  <li>Create a key pair with the ssh.com client: Settings - User Authentication - Generate New....</li>
  <li>I use Key type DSA; key length 2048.</li>
  <li>Copy the public key generated by the ssh.com client to the server into the ~/.ssh folder.</li>
  <li>The keys are in C:\Documents and Settings\%USERNAME%\Application Data\SSH\UserKeys.</li>
  <li>Use the ssh-keygen command on the server to convert the key:
<pre># cd ~/.ssh
# ssh-keygen -i -f keyfilename.pub &gt;&gt; authorized_keys2
</pre></li>
</ul>

<i>Notice:</i> We used a DSA key, RSA is also possible. The key is not protected by a password.
<h3>Using putty for Windows</h3>
<a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">Putty</a><span class="fn">http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html</span> is a simple and free ssh client for Windows. 
<ul>
  <li>Create a key pair with the puTTYgen program.</li>
  <li>Save the public and private keys (for example into C:\Documents and Settings\%USERNAME%\.ssh).</li>
  <li>Copy the public key to the server into the ~/.ssh folder:
    <pre># scp .ssh/puttykey.pub root@192.168.51.254:.ssh/</pre></li>
  <li>Use the ssh-keygen command on the server to convert the key for OpenSSH:
<pre># cd ~/.ssh
# ssh-keygen -i -f puttykey.pub &gt;&gt; authorized_keys2
</pre></li>
<li>Point the private key location in the putty settings: Connection - SSH - Auth</li>
</ul>

<h2 id="sshfingerprint">Check fingerprint</h2>
At the first login, ssh will ask if the unknown host with the fingerprint has to be stored in the known hosts. To avoid a man-in-the-middle attack the administrator of the server can send you the server fingerprint which is then compared on the first login. Use <code>ssh-keygen -l</code> to get the fingerprint (on the server):
<pre># ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub      <span class="cmt"># For RSA key</span>
2048 61:33:be:9b:ae:6c:36:31:fd:83:98:b7:99:2d:9f:cd /etc/ssh/ssh_host_rsa_key.pub
# ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub      <span class="cmt"># For DSA key (default)</span>
2048 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee /etc/ssh/ssh_host_dsa_key.pub
</pre>
Now the client connecting to this server can verify that he is connecting to the right server:
<pre>
# ssh linda
The authenticity of host 'linda (192.168.16.54)' can't be established.
DSA key fingerprint is 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee.
Are you sure you want to continue connecting (yes/no)? yes
</pre>
<h2 id="scp">Secure file transfer</h2>
Some simple commands:<br/>
<pre># scp file.txt host-two:/tmp
# scp joe@host-two:/www/*.html /www/tmp
# scp -r joe@host-two:/www /www/tmp
</pre>
In Konqueror or Midnight Commander it is possible to access a remote file system with the address <strong>fish://user@gate</strong>. However the implementation is very slow.<br/>
Furthermore it is possible to mount a remote folder with <strong>sshfs</strong> a file system client based on SCP. <a href="http://fuse.sourceforge.net/sshfs.html">See fuse sshfs</a><span class="fn">http://fuse.sourceforge.net/sshfs.html</span>.

<h2 id="sshtunnel">Tunneling</h2>
SSH tunneling allows to forward or reverse forward a port over the SSH connection, thus securing the traffic and accessing ports which would otherwise be blocked. This only works with TCP. The general nomenclature for forward and reverse is (see also <a href="#sshnat">ssh and NAT example</a>):
<pre># ssh -L localport:desthost:destport user@gate  <span class="cmt"># desthost as seen from the gate</span>
# ssh -R destport:desthost:localport user@gate  <span class="cmt"># forwards your localport to destination</span>
# ssh -X user@gate   <span class="cmt"># To force X forwarding</span>
</pre>
This will connect to gate and forward the local port to the host desthost:destport. Note desthost is the destination host <i>as seen by the gate</i>, so if the connection is to the gate, then desthost is localhost. More than one port forward is possible.
<h3>Direct forward on the gate</h3>
Let say we want to access the CVS (port 2401) and http (port 80) which are running on the gate. This is the simplest example, desthost is thus localhost, and we use the port 8080 locally instead of 80 so we don't need to be root. Once the ssh session is open, both services are accessible on the local ports.
<pre># ssh -L 2401:localhost:2401 -L 8080:localhost:80 user@gate</pre>
<h3>Netbios and remote desktop forward to a second server</h3>
Let say a Windows smb server is behind the gate and is not running ssh. We need access to the smb share and also remote desktop to the server.
<pre># ssh -L 139:smbserver:139 -L 3388:smbserver:3389 user@gate</pre>
The smb share can now be accessed with \\127.0.0.1\, but only if the local share is disabled, because <i>the local share is listening on port 139</i>.<br/>
It is possible to keep the local share enabled, for this we need to create a new virtual device with a new IP address for the tunnel, the smb share will be connected over this address. Furthermore <i>the local RDP is already listening on 3389</i>, so we choose 3388. For this example let's use a virtual IP of 10.1.1.1.<br/>
<ul>
<li>With putty use Source port=10.1.1.1:139. It is possible to create multiple loop devices and tunnel. On Windows 2000, only putty worked for me.</li>
<li>With the ssh.com client, disable "Allow local connections only". Since ssh.com will bind to all addresses, only a single share can be connected.</li>
</ul>
Now create the loopback interface with IP 10.1.1.1:
<ul>
<li># System-&gt;Control Panel-&gt;Add Hardware # Yes, Hardware is already connected
# Add a new hardware device (at bottom).</li>
<li># Install the hardware that I manually select # Network adapters # Microsoft , Microsoft Loopback Adapter.</li>
<li>Configure the IP address of the fake device to 10.1.1.1 mask 255.255.255.0, no gateway.</li>
<li>advanced-&gt;WINS, Enable LMHosts Lookup; Disable NetBIOS over TCP/IP.</li>
<li># Enable Client for Microsoft Networks. # Disable File and Printer Sharing for Microsoft Networks.</li>
</ul>
I HAD to reboot for this to work. Now connect to the smb share with \\10.1.1.1 and remote desktop to 10.1.1.1:3388.
<h4>Debug</h4>
If it is not working:
<ul>
<li>Are the ports forwarded: netstat -an? Look at 0.0.0.0:139 or 10.1.1.1:139</li>
<li>Does telnet 10.1.1.1 139 connect?</li>
<li>You need the checkbox "Local ports accept connections from other hosts".</li>
<li>Is "File and Printer Sharing for Microsoft Networks" disabled on the loopback interface?</li>
</ul>

<h3 id="sshnat">Connect two clients behind NAT</h3>
Suppose two clients are behind a NAT gateway and client cliadmin has to connect to client cliuser (the destination), both can login to the gate with ssh and are running Linux with sshd. You don't need root access anywhere as long as the ports on gate are above 1024. We use 2022 on gate. Also since the gate is used locally, the option GatewayPorts is not necessary.<br/>
On client cliuser (from destination to gate):
<pre># ssh -R 2022:localhost:22 user@gate            <span class="cmt"># forwards client 22 to gate:2022</span></pre>
On client cliadmin (from host to gate):
<pre># ssh -L 3022:localhost:2022 admin@gate         <span class="cmt"># forwards client 3022 to gate:2022</span></pre>
Now the admin can connect directly to the client cliuser with:
<pre># ssh -p 3022 admin@localhost                   <span class="cmt"># local:3022 -&gt; gate:2022 -&gt; client:22</span></pre>

<h3>Connect to VNC behind NAT</h3>
Suppose a Windows client with VNC listening on port 5900 has to be accessed from behind NAT.
On client cliwin to gate:
<pre># ssh -R 15900:localhost:5900 user@gate</pre>
On client cliadmin (from host to gate):
<pre># ssh -L 5900:localhost:15900 admin@gate</pre>
Now the admin can connect directly to the client VNC with:
<pre># vncconnect -display :0 localhost</pre>
</div>

<div id="vpn"><h1><a>VPN with SSH</a></h1>
As of version 4.3, OpenSSH can use the tun/tap device to encrypt a tunnel. This is very similar to other TLS based VPN solutions like OpenVPN. One advantage with SSH is that there is no need to install and configure additional software. Additionally the tunnel uses the SSH authentication like pre shared keys. The drawback is that the encapsulation is done over TCP which might result in poor performance on a slow link. Also the tunnel is relying on a single (fragile) TCP connection.  This technique is very useful for a quick IP based VPN setup. There is no limitation as with the single TCP port forward, all layer 3/4 protocols like ICMP, TCP/UDP, etc. are forwarded over the VPN. In any case, the following options are needed in the sshd_conf file:
<pre>PermitRootLogin yes
PermitTunnel yes
</pre>

<h2 id="sshp2p">Single P2P connection</h2>
Here we are connecting two hosts, hclient and hserver with a peer to peer tunnel. The connection is <i>started from hclient</i> to hserver and is done as root. The tunnel end points are 10.0.1.1 (server) and 10.0.1.2 (client) and we create a device tun5 (this could also be an other number). The procedure is very simple:
<ul>
  <li>Connect with SSH using the tunnel option -w</li>
  <li>Configure the IP addresses of the tunnel. Once on the server and once on the client.</li>
</ul>
<h3>Connect to the server</h3>
Connection started on the client and commands are executed on the server.
<h4>Server is on Linux</h4>
<pre><span class="cmt">cli&gt;#</span> ssh -w5:5 root@hserver
<span class="cmt">srv&gt;#</span> ifconfig tun5 10.0.1.1 netmask 255.255.255.252   <span class="cmt"># Executed on the server shell</span>
</pre>
<h4>Server is on FreeBSD</h4>
<pre><span class="cmt">cli&gt;#</span> ssh -w5:5 root@hserver
<span class="cmt">srv&gt;#</span> ifconfig tun5 10.0.1.1 10.0.1.2                  <span class="cmt"># Executed on the server shell</span>
</pre>

<h3>Configure the client</h3>
Commands executed on the client:
<pre><span class="cmt">cli&gt;#</span> ifconfig tun5 10.0.1.2 netmask 255.255.255.252   <span class="cmt"># Client is on Linux</span>
<span class="cmt">cli&gt;#</span> ifconfig tun5 10.0.1.2 10.0.1.1                  <span class="cmt"># Client is on FreeBSD</span>
</pre>
The two hosts are now connected and can transparently communicate with any layer 3/4 protocol using the tunnel IP addresses.

<h2 id="sshg2g">Connect two networks</h2>
In addition to the p2p setup above, it is more useful to connect two private networks with an SSH VPN using two gates. Suppose for the example, netA is 192.168.51.0/24 and netB 192.168.16.0/24. The procedure is similar as above, we only need to add the routing. NAT must be activated on the private interface only if the gates are not the same as the default gateway of their network.<br/>
192.168.51.0/24 (netA)|gateA &lt;-&gt; gateB|192.168.16.0/24 (netB)<br/>
<ul>
  <li>Connect with SSH using the tunnel option -w.</li>
  <li>Configure the IP addresses of the tunnel. Once on the server and once on the client.</li>
  <li>Add the routing for the two networks.</li>
  <li>If necessary, activate NAT on the private interface of the gate.</li>
</ul>
The setup is <i>started from gateA in netA</i>.
<h3>Connect from gateA to gateB</h3>
Connection is started from gateA and commands are executed on gateB.
<h4>gateB is on Linux</h4>
<pre><span class="cmt">gateA&gt;#</span> ssh -w5:5 root@gateB
<span class="cmt">gateB&gt;#</span> ifconfig tun5 10.0.1.1 netmask 255.255.255.252 <span class="cmt"># Executed on the gateB shell</span>
<span class="cmt">gateB&gt;#</span> route add -net 192.168.51.0 netmask 255.255.255.0 dev tun5
<span class="cmt">gateB&gt;#</span> echo 1 &gt; /proc/sys/net/ipv4/ip_forward        <span class="cmt"># Only needed if not default gw</span>
<span class="cmt">gateB&gt;#</span> iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
</pre>
<h4>gateB is on FreeBSD</h4>
<pre><span class="cmt">gateA&gt;#</span> ssh -w5:5 root@gateB                          <span class="cmt"># Creates the tun5 devices</span>
<span class="cmt">gateB&gt;#</span> ifconfig tun5 10.0.1.1 10.0.1.2               <span class="cmt"># Executed on the gateB shell</span>
<span class="cmt">gateB&gt;#</span> route add 192.168.51.0/24 10.0.1.2
<span class="cmt">gateB&gt;#</span> sysctl net.inet.ip.forwarding=1               <span class="cmt"># Only needed if not default gw</span>
<span class="cmt">gateB&gt;#</span> natd -s -m -u -dynamic -n fxp0                <span class="cmt"># see <a class="xref" href="#nat">NAT</a></span>
<span class="cmt">gateA&gt;#</span> sysctl net.inet.ip.fw.enable=1
</pre>

<h3>Configure gateA</h3>
Commands executed on gateA:
<h4>gateA is on Linux</h4>
<pre><span class="cmt">gateA&gt;#</span> ifconfig tun5 10.0.1.2 netmask 255.255.255.252
<span class="cmt">gateA&gt;#</span> route add -net 192.168.16.0 netmask 255.255.255.0 dev tun5
<span class="cmt">gateA&gt;#</span> echo 1 &gt; /proc/sys/net/ipv4/ip_forward
<span class="cmt">gateA&gt;#</span> iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
</pre>
<h4>gateA is on FreeBSD</h4>
<pre><span class="cmt">gateA&gt;#</span> ifconfig tun5 10.0.1.2 10.0.1.1
<span class="cmt">gateA&gt;#</span> route add 192.168.16.0/24 10.0.1.2
<span class="cmt">gateA&gt;#</span> sysctl net.inet.ip.forwarding=1
<span class="cmt">gateA&gt;#</span> natd -s -m -u -dynamic -n fxp0                <span class="cmt"># see <a class="xref" href="#nat">NAT</a></span>
<span class="cmt">gateA&gt;#</span> sysctl net.inet.ip.fw.enable=1
</pre>
The two private networks are now transparently connected via the SSH VPN. The IP forward and NAT settings are only necessary if the gates are not the default gateways. In this case the clients would not know where to forward the response, and nat must be activated.
</div>

<div id="rsync"><h1><a>RSYNC</a></h1>
Rsync can almost completely replace cp and scp, furthermore interrupted transfers are efficiently restarted. A trailing slash (and the absence thereof) has different meanings, the man page is good... Here some examples:<br/>
Copy the directories with full content:
<pre># rsync -a /home/colin/ /backup/colin/
# rsync -a /var/ /var_bak/
# rsync -aR --delete-during /home/user/ /backup/      <span class="cmt"># use relative (see below)</span>
</pre>
Same as before but over the network and with compression. Rsync uses SSH for the transport per default and will use the ssh key if they are set. Use ":" as with SCP. A typical remote copy:
<pre># rsync -axSRzv /home/user/ user@server:/backup/user/</pre>
Exclude any directory tmp within /home/user/ and keep the relative folders hierarchy, that is the remote directory will have the structure /backup/home/user/. This is typically used for backups.
<pre># rsync -azR --exclude /tmp/ /home/user/ user@server:/backup/</pre>

Use port 20022 for the ssh connection:
<pre># rsync -az -e 'ssh -p 20022' /home/colin/ user@server:/backup/colin/</pre>
Using the rsync daemon (used with "::") is much faster, but not encrypted over ssh. The location of /backup is defined by the configuration in /etc/rsyncd.conf. The variable RSYNC_PASSWORD can be set to avoid the need to enter the password manually.
<pre># rsync -axSRz /home/ ruser@hostname::rmodule/backup/
# rsync -axSRz ruser@hostname::rmodule/backup/ /home/    <span class="cmt"># To copy back</span>
</pre>
Some important options:
<ul style="list-style-type: none;">
  <li><code>-a, --archive</code>       archive mode; same as -rlptgoD (no -H)</li>
  <li><code>-r, --recursive</code>       recurse into directories</li>
  <li><code>-R, --relative</code>       use relative path names</li>
  <li><code>-H, --hard-links</code>       preserve hard links</li>
  <li><code>-S, --sparse</code>       handle sparse files efficiently</li>
  <li><code>-x, --one-file-system</code>       don't cross file system boundaries</li>
  <li><code> --exclude=PATTERN</code>       exclude files matching PATTERN</li>
  <li><code> --delete-during</code>       receiver deletes during xfer, not before</li>
  <li><code> --delete-after</code>       receiver deletes after transfer, not before</li>
</ul>

<h2 id="winrsync">Rsync on Windows</h2>
Rsync is available for Windows through cygwin or as stand-alone packaged in <a href="http://sourceforge.net/projects/sereds/">cwrsync</a><span class="fn">http://sourceforge.net/projects/sereds</span>. This is very convenient for automated backups. Install one of them (<i>not both</i>) and add the path to the Windows system variables: # Control Panel -&gt; System -&gt; tab Advanced, button Environment Variables. Edit the "Path" system variable and add the full path to the installed rsync, e.g. C:\Program Files\cwRsync\bin or C:\cygwin\bin. This way the commands <code>rsync</code> and <code>ssh</code> are available in a Windows command shell.
<h3>Public key authentication</h3>
Rsync is automatically tunneled over SSH and thus uses the SSH authentication on the server. Automatic backups have to avoid a user interaction, for this the SSH public key authentication can be used and the rsync command will run without a password.<br/>
All the following commands are executed within a Windows console. In a console (Start -&gt; Run -&gt; cmd) create and upload the key as described in <a href="#ssh">SSH</a>, change "user" and "server" as appropriate. If the file authorized_keys2 does not exist yet, simply copy id_dsa.pub to authorized_keys2 and upload it.
<pre># ssh-keygen -t dsa -N ''                   <span class="cmt"># Creates a public and a private key</span>
# rsync user@server:.ssh/authorized_keys2 . <span class="cmt"># Copy the file locally from the server</span>
# cat id_dsa.pub &gt;&gt; authorized_keys2        <span class="cmt"># Or use an editor to add the key</span>
# rsync authorized_keys2 user@server:.ssh/  <span class="cmt"># Copy the file back to the server</span>
# del authorized_keys2                      <span class="cmt"># Remove the local copy</span>
</pre>
Now test it with (in one line):
<pre>rsync -rv "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
'user@server:My\ Documents/'
</pre>
<h3>Automatic backup</h3>
Use a batch file to automate the backup and add the file in the scheduled tasks (Programs -&gt; Accessories -&gt; System Tools -&gt; Scheduled Tasks). For example create the file backup.bat and replace user@server.
<pre>@ECHO OFF
REM rsync the directory My Documents
SETLOCAL
SET CWRSYNCHOME=C:\PROGRAM FILES\CWRSYNC
SET CYGWIN=nontsec
SET CWOLDPATH=%PATH%
REM uncomment the next line when using cygwin
SET PATH=%CWRSYNCHOME%\BIN;%PATH%
echo Press Control-C to abort
rsync -av "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
'user@server:My\ Documents/'
pause
</pre>
</div>

<div id="sudo"><h1><a>SUDO</a></h1>
Sudo is a standard way to give users some administrative rights without giving out the root password. Sudo is very useful in a multi user environment with a mix of server and workstations. Simply call the command with sudo:
<pre># sudo /etc/init.d/dhcpd restart            <span class="cmt"># Run the rc script as root</span>
# sudo -u sysadmin whoami                   <span class="cmt"># Run cmd as an other user</span>
</pre>
<h2>Configuration</h2>
Sudo is configured in <code>/etc/sudoers</code> and must only be edited with <code>visudo</code>. The basic syntax is (the lists are comma separated):
<pre>user hosts = (runas) commands          <span class="cmt"># In /etc/sudoers</span></pre>        
<ul style="list-style-type: none; page-break-inside: avoid;">
  <li><code>users</code> one or more users or %group (like %wheel) to gain the rights</li>
  <li><code>hosts</code> list of hosts (or ALL)</li>
  <li><code>runas</code> list of users (or ALL) that the command rule can be run as. It is enclosed in ( )!</li>
  <li><code>commands</code> list of commands (or ALL) that will be run as root or as (runas)</li>
</ul>
Additionally those keywords can be defined as alias, they are called User_Alias, Host_Alias, Runas_Alias and Cmnd_Alias. This is useful for larger setups. Here a sudoers example:
<pre># cat /etc/sudoers
<span class="cmt"># Host aliases are subnets or hostnames.</span>
Host_Alias   DMZ     = 212.118.81.40/28
Host_Alias   DESKTOP = work1, work2

<span class="cmt"># User aliases are a list of users which can have the same rights</span>
User_Alias   ADMINS  = colin, luca, admin
User_Alias   DEVEL   = joe, jack, julia
Runas_Alias  DBA     = oracle,pgsql

<span class="cmt"># Command aliases define the full path of a list of commands</span>
Cmnd_Alias   SYSTEM  = /sbin/reboot,/usr/bin/kill,/sbin/halt,/sbin/shutdown,/etc/init.d/
Cmnd_Alias   PW      = /usr/bin/passwd [A-z]*, !/usr/bin/passwd root <span class="cmt"># Not root pwd!</span>
Cmnd_Alias   DEBUG   = /usr/sbin/tcpdump,/usr/bin/wireshark,/usr/bin/nmap
</pre><pre><span class="cmt"># The actual rules</span>
root,ADMINS  ALL     = (ALL) NOPASSWD: ALL    <span class="cmt"># ADMINS can do anything w/o a password.</span>
DEVEL        DESKTOP = (ALL) NOPASSWD: ALL    <span class="cmt"># Developers have full right on desktops</span>
DEVEL        DMZ     = (ALL) NOPASSWD: DEBUG  <span class="cmt"># Developers can debug the DMZ servers.</span>

<span class="cmt"># User sysadmin can mess around in the DMZ servers with some commands.</span>
sysadmin     DMZ     = (ALL) NOPASSWD: SYSTEM,PW,DEBUG
sysadmin     ALL,!DMZ = (ALL) NOPASSWD: ALL   <span class="cmt"># Can do anything outside the DMZ.</span>
%dba         ALL     = (DBA) ALL              <span class="cmt"># Group dba can run as database user.</span>

<span class="cmt"># anyone can mount/unmount a cd-rom on the desktop machines</span>
ALL          DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom
</pre> 

</div>

<div id="crypt"><h1><a>Encrypt Files</a></h1>
<h2>OpenSSL</h2>
<h3>A single file</h3>
Encrypt and decrypt:
<pre># openssl des -salt -in file -out file.des
# openssl des -d -salt -in file.des -out file
</pre>
Note that the file can of course be a tar archive.
    
<h3>tar and encrypt a whole directory</h3>
<pre># tar -cf - directory | openssl des -salt -out directory.tar.des      <span class="cmt"># Encrypt</span>
# openssl des -d -salt -in directory.tar.des | tar -x                 <span class="cmt"># Decrypt</span>
</pre>
    
<h3>tar zip and encrypt a whole directory</h3>
<pre># tar -zcf - directory | openssl des -salt -out directory.tar.gz.des  <span class="cmt"># Encrypt</span>
# openssl des -d -salt -in directory.tar.gz.des | tar -xz             <span class="cmt"># Decrypt</span>
</pre>

<ul>
<li>Use -k mysecretpassword after des to avoid the interactive password request. However note that this is highly insecure.</li>
<li>Use <strong>des3</strong> instead of <strong>des</strong> to get even stronger encryption (Triple-DES Cipher). This uses also more CPU.</li>
</ul>

<h2>GPG</h2>
<a href="http://gnupg.org/">GnuPG</a> is well known to encrypt and sign emails or any data. Furthermore gpg and also provides an advanced key management system. This section only covers files encryption, not email usage, signing or the Web-Of-Trust.<br/>
The simplest encryption is with a symmetric cipher. In this case the file is encrypted with a password and anyone who knows the password can decrypt it, thus the keys are not needed. Gpg adds an extention ".gpg" to the encrypted file names.
<pre># gpg -c file                        <span class="cmt"># Encrypt file with password</span>
# gpg file.gpg                       <span class="cmt"># Decrypt file (optionally -o otherfile)</span>
</pre>
<h3>Using keys</h3>
For more details see <a href="http://www.madboa.com/geek/gpg-quickstart">GPG Quick Start</a><span class="fn">http://www.madboa.com/geek/gpg-quickstart</span> and <a href="http://aplawrence.com/Basics/gpg.html">GPG/PGP Basics</a><span class="fn">http://aplawrence.com/Basics/gpg.html</span> and the <a href="http://gnupg.org/documentation">gnupg documentation</a><span class="fn">http://gnupg.org/documentation</span> among others.<br/>
The private and public keys are the heart of asymmetric cryptography. What is important to remember:
<ul>
<li>Your public key is used by <i>others</i> to encrypt files that only you as the receiver can decrypt (not even the one who encrypted the file can decrypt it). The public key is thus meant to be distributed.</li>
<li>Your private key is encrypted with your passphrase and is used to decrypt files which where encrypted with <i>your</i> public key. The private key must be kept <b>secure</b>. Also if the key or passphrase is lost, so are all the files encrypted with your public key.</li>
<li>The key files are called keyrings as they can contain more than one key.</li>
</ul>
First generate a key pair. The defaults are fine, however you will have to enter at least your full name and email and optionally a comment. The comment is useful to create more than one key with the same name and email. Also you should use a "passphrase", not a simple password.
<pre># gpg --gen-key                      <span class="cmt"># This can take a long time</span></pre>
The keys are stored in ~/.gnupg/ on Unix, on Windows they are typically stored in<br/>
C:/Documents and Settings/%USERNAME%/Application Data/gnupg/.
<pre>~/.gnupg/pubring.gpg                 <span class="cmt"># Contains your public keys and all others imported</span>
~/.gnupg/secring.gpg                 <span class="cmt"># Can contain more than one private key</span>
</pre>
Short reminder on most used options:
<ul style="list-style-type: none; page-break-inside: avoid;">
  <li><b>-e</b> encrypt data</li>
  <li><b>-d</b> decrypt data</li>
  <li><b>-r</b> NAME encrypt for recipient NAME (or 'Full Name' or 'email@domain')</li>
  <li><b>-a</b> create ascii armored output of a key</li>
  <li><b>-o</b> use as output file</li>
</ul>
The examples use 'Your Name' and 'Alice' as the keys are referred to by the email or full name or partial name. For example I can use 'Colin' or 'c@cb.vu' for my key [Colin Barschel (cb.vu) &lt;c@cb.vu&gt;].
<h3>Encrypt for personal use only</h3>
No need to export/import any key for this. You have both already.
<pre># gpg -e -r 'Your Name' file                  <span class="cmt"># Encrypt with your public key</span>
# gpg -o file -d file.gpg                     <span class="cmt"># Decrypt. Use -o or it goes to stdout</span>
</pre>
<h3>Encrypt - Decrypt with keys</h3>
First you need to export your public key for someone else to use it. And you need to import the public say from Alice to encrypt a file for her. You can either handle the keys in simple ascii files or use a public key server.<br/>
For example Alice export her public key and you import it, you can then encrypt a file for her. That is only Alice will be able to decrypt it.
<pre># gpg -a -o alicekey.asc --export 'Alice'     <span class="cmt"># Alice exported her key in ascii file.</span>
# gpg --send-keys --keyserver subkeys.pgp.net KEYID   <span class="cmt"># Alice put her key on a server.</span>
# gpg --import alicekey.asc                   <span class="cmt"># You import her key into your pubring.</span>
# gpg --search-keys --keyserver subkeys.pgp.net 'Alice' <span class="cmt"># or get her key from a server.</span>
</pre>
Once the keys are imported it is very easy to encrypt or decrypt a file:
<pre># gpg -e -r 'Alice' file                      <span class="cmt"># Encrypt the file for Alice.</span>
# gpg -d file.gpg -o file                     <span class="cmt"># Decrypt a file encrypted by Alice for you.</span>
</pre>
<h3>Key administration</h3>
<pre># gpg --list-keys                             <span class="cmt"># list public keys and see the KEYIDS</span>
    <span class="cmt">The KEYID follows the '/' e.g. for: pub   1024D/D12B77CE the KEYID is D12B77CE</span>
# gpg --gen-revoke 'Your Name'                <span class="cmt"># generate revocation certificate</span>
# gpg --list-secret-keys                      <span class="cmt"># list private keys</span>
# gpg --delete-keys NAME                      <span class="cmt"># delete a public key from local key ring</span>
# gpg --delete-secret-key NAME                <span class="cmt"># delete a secret key from local key ring</span>
# gpg --fingerprint KEYID                     <span class="cmt"># Show the fingerprint of the key</span>
# gpg --edit-key KEYID                        <span class="cmt"># Edit key (e.g sign or add/del email)</span>
</pre>

</div>

<div id="cryptpart"><h1><a>Encrypt Partitions</a></h1>
<p class="xrefp"><a class="xrefp" href="#wluks">Linux with LUKS</a> | <a class="xrefp" href="#woluks">Linux dm-crypt only</a> | <a class="xrefp" href="#bsdgeli">FreeBSD GELI</a> | <a class="xrefp" href="#bsdpwd">FBSD pwd only</a></p>
There are (many) other alternative methods to encrypt disks, I only show here the methods I know and use. Keep in mind that the security is only good as long the OS has not been tempered with. An intruder could easily record the password from the keyboard events. Furthermore the data is freely accessible when the partition is <i>attached</i> and will not prevent an intruder to have access to it in this state.
<h2 id="dm-crypt">Linux</h2>
Those instructions use the Linux <code>dm-crypt</code> (device-mapper) facility available on the 2.6 kernel. In this example, lets encrypt the partition <code>/dev/sdc1</code>, it could be however any other partition or disk, or USB or a file based partition created with <code>losetup</code>. In this case we would use <code>/dev/loop0</code>. See <a href="#losetup">file image partition</a>. The device mapper uses labels to identify a partition. We use <code>sdc1</code> in this example, but it could be any string.
<h3 id="wluks">dm-crypt with LUKS</h3>
LUKS with dm-crypt has better encryption and makes it possible to have multiple passphrase for the same partition or to change the password easily. To test if LUKS is available, simply type <code># cryptsetup --help</code>, if nothing about LUKS shows up, use the instructions below <a href="#woluks">Without LUKS</a>. First create a partition if necessary: <code>fdisk /dev/sdc</code>.
<h4>Create encrypted partition</h4>
<pre># dd if=/dev/urandom of=/dev/sdc1          <span class="cmt"># Optional. For paranoids only (takes days)</span>
# cryptsetup -y luksFormat /dev/sdc1       <span class="cmt"># This destroys any data on sdc1</span>
# cryptsetup luksOpen /dev/sdc1 sdc1
# mkfs.ext3 /dev/mapper/sdc1               <span class="cmt"># create ext3 file system</span>
# mount -t ext3 /dev/mapper/sdc1 /mnt
# umount /mnt
# cryptsetup luksClose sdc1                <span class="cmt"># Detach the encrypted partition</span></pre>
<h4>Attach</h4>
<pre># cryptsetup luksOpen /dev/sdc1 sdc1
# mount -t ext3 /dev/mapper/sdc1 /mnt</pre>
<h4>Detach</h4>
<pre># umount /mnt
# cryptsetup luksClose sdc1
</pre>
<h3 id="woluks">dm-crypt without LUKS</h3>
<pre># cryptsetup -y create sdc1 /dev/sdc1      <span class="cmt"># or any other partition like /dev/loop0</span>
# dmsetup ls                               <span class="cmt"># check it, will display: sdc1 (254, 0)</span>
# mkfs.ext3 /dev/mapper/sdc1               <span class="cmt"># This is done only the first time!</span>
# mount -t ext3 /dev/mapper/sdc1 /mnt
# umount /mnt/
# cryptsetup remove sdc1                   <span class="cmt"># Detach the encrypted partition</span>
</pre>
Do exactly the same (without the mkfs part!) to re-attach the partition. If the password is not correct, the mount command will fail. In this case simply remove the map sdc1 (<code>cryptsetup remove sdc1</code>) and create it again.
<h2 id="bsdgeli">FreeBSD</h2>
The two popular FreeBSD disk encryption modules are <code>gbde</code> and <code>geli</code>. I now use geli because it is faster and also uses the crypto device for hardware acceleration. See The <a href="http://www.freebsd.org/handbook/disks-encrypting.html">FreeBSD handbook Chapter 18.6</a><span class="fn">http://www.freebsd.org/handbook/disks-encrypting.html</span> for all the details. The geli module must be loaded or compiled into the kernel:
<pre>options GEOM_ELI
device crypto                                       <span class="cmt"># or as module:</span>
# echo 'geom_eli_load="YES"' &gt;&gt; /boot/loader.conf   <span class="cmt"># or do: kldload geom_eli</span>
</pre>
<h3>Use password and key</h3>
I use those settings for a typical disk encryption, it uses a passphrase AND a key to encrypt the master key. That is you need both the password and the generated key <code>/root/ad1.key</code> to attach the partition. The master key is stored inside the partition and is not visible. See below for typical USB or file based image.
<h4>Create encrypted partition</h4>
<pre>
# dd if=/dev/random of=/root/ad1.key bs=64 count=1  <span class="cmt"># this key encrypts the mater key</span>
# geli init -s 4096 -K /root/ad1.key /dev/ad1       <span class="cmt"># -s 8192 is also OK for disks</span>
# geli attach -k /root/ad1.key /dev/ad1             <span class="cmt"># DO make a backup of /root/ad1.key</span>
# dd if=/dev/random of=/dev/ad1.eli bs=1m           <span class="cmt"># Optional and takes a long time</span>
# newfs /dev/ad1.eli                                <span class="cmt"># Create file system</span>
# mount /dev/ad1.eli /mnt
</pre>
<h4>Attach</h4>
<pre># geli attach -k /root/ad1.key /dev/ad1
# fsck -ny -t ffs /dev/ad1.eli                      <span class="cmt"># In doubt check the file system</span>
# mount /dev/ad1.eli /mnt
</pre>
<h4>Detach</h4>
The detach procedure is done automatically on shutdown.
<pre># umount /mnt
# geli detach /dev/ad1.eli
</pre>
<h4>/etc/fstab</h4>
The encrypted partition can be configured to be mounted with /etc/fstab. The password will be prompted when booting. The following settings are required for this example:
<pre># grep geli /etc/rc.conf
geli_devices="ad1"
geli_ad1_flags="-k /root/ad1.key"
# grep geli /etc/fstab
/dev/ad1.eli         /home/private              ufs             rw      0       0
</pre>
<h3 id="bsdpwd">Use password only</h3>
It is more convenient to encrypt a USB stick or file based image with a passphrase only and no key. In this case it is not necessary to carry the additional key file around. The procedure is very much the same as above, simply without the key file. Let's encrypt a file based image <code>/cryptedfile</code> of 1 GB.
<pre># dd if=/dev/zero of=/cryptedfile bs=1M count=1000  <span class="cmt"># 1 GB file</span>
# mdconfig -at vnode -f /cryptedfile
# geli init /dev/md0                                <span class="cmt"># encrypts with password only</span>
# geli attach /dev/md0
# newfs -U -m 0 /dev/md0.eli
# mount /dev/md0.eli /mnt
# umount /dev/md0.eli
# geli detach md0.eli
</pre>
It is now possible to mount this image on an other system with the password only.
<pre># mdconfig -at vnode -f /cryptedfile
# geli attach /dev/md0
# mount /dev/md0.eli /mnt
</pre>
</div>

<div id="certs"><h1><a>SSL Certificates</a></h1>
So called SSL/TLS certificates are cryptographic public key certificates and are composed of a public and a private key. The certificates are used to authenticate the endpoints and encrypt the data. They are used for example on a web server (https) or mail server (imaps).
<h2>Procedure</h2>
<ul>
<li>We need a certificate authority to sign our certificate. This step is
  usually provided by a vendor like Thawte, Verisign, etc., however we can also create our own.</li>
<li>Create a certificate signing request. This request is like an unsigned certificate (the public part) and already contains all necessary information. The certificate request is normally sent to the authority vendor for signing. This step also creates the private key on the local machine.</li>
<li>Sign the certificate with the certificate authority.</li>
<li>If necessary join the certificate and the key in a single file to be used by the application (web server, mail server etc.).</li>
</ul>

<h2>Configure OpenSSL</h2>
We use /usr/local/certs as directory for this example check or edit /etc/ssl/openssl.cnf accordingly to your settings so you know where the files will be created. Here are the relevant part of openssl.cnf:
<pre>[ CA_default ]
dir             = /usr/local/certs/CA       <span class="cmt"># Where everything is kept</span>
certs           = $dir/certs                <span class="cmt"># Where the issued certs are kept</span>
crl_dir         = $dir/crl                  <span class="cmt"># Where the issued crl are kept</span>
database        = $dir/index.txt            <span class="cmt"># database index file.</span>
</pre>
Make sure the directories exist or create them
<pre># mkdir -p /usr/local/certs/CA
# cd /usr/local/certs/CA
# mkdir certs crl newcerts private
# echo "01" &gt; serial                        <span class="cmt"># Only if serial does not exist</span>
# touch index.txt
</pre>

<h2 id="createca">Create a certificate authority</h2>

If you do not have a certificate authority from a vendor, you'll have to create your own. This step is not necessary if one intend to use a vendor to sign the request. To make a certificate authority (CA):
<pre># openssl req -new -x509 -days 730 -config /etc/ssl/openssl.cnf \
-keyout CA/private/cakey.pem -out CA/cacert.pem
</pre>

<h2 id="createreq">Create a certificate signing request</h2>
To make a new certificate (for mail server or web server for example), first create a request certificate with its private key. If your application do not support encrypted private key (for example UW-IMAP does not), then disable encryption with <code>-nodes</code>.
<pre># openssl req -new -keyout newkey.pem -out newreq.pem \
-config /etc/ssl/openssl.cnf
# openssl req -nodes -new -keyout newkey.pem -out newreq.pem \
-config /etc/ssl/openssl.cnf                <span class="cmt"># No encryption for the key</span>
</pre>

<h2 id="signcert">Sign the certificate</h2>
The certificate request has to be signed by the CA to be valid, this step is usually done by the vendor. <i>Note: replace "servername" with the name of your server in the next commands</i>.
<pre># cat newreq.pem newkey.pem &gt; new.pem
# openssl ca -policy policy_anything -out servernamecert.pem \
-config /etc/ssl/openssl.cnf -infiles new.pem
# mv newkey.pem servernamekey.pem
</pre>
Now servernamekey.pem is the private key and servernamecert.pem is the server certificate.

<h2>Create united certificate</h2>
The IMAP server wants to have both private key and server certificate in the same file. And in general, this is also easier to handle, but the file has to be kept securely!. Apache also can deal with it well. Create a file servername.pem containing both the certificate and key.
<ul>
  <li>Open the private key (servernamekey.pem) with a text editor and copy the private key into the "servername.pem" file.</li>
  <li>Do the same with the server certificate (servernamecert.pem).</li>
</ul>
The final servername.pem file should look like this:<br/><br/>
<pre>-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDutWy+o/XZ/[...]qK5LqQgT3c9dU6fcR+WuSs6aejdEDDqBRQ
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIERzCCA7CgAwIBAgIBBDANB[...]iG9w0BAQQFADCBxTELMAkGA1UEBhMCREUx
-----END CERTIFICATE-----
</pre>
What we have now in the directory /usr/local/certs/:
<ul style="list-style-type: none;">
  <li>CA/private/cakey.pem <i>(CA server private key)</i></li>
  <li>CA/cacert.pem <i>(CA server public key)</i></li>
  <li>certs/servernamekey.pem <i>(server private key)</i></li>
  <li>certs/servernamecert.pem <i>(server signed certificate)</i></li>
  <li>certs/servername.pem <i>(server certificate with private key)</i></li>
</ul>
Keep the private key secure!

<h2 id="viewcert">View certificate information</h2>
To view the certificate information simply do:
<pre># openssl x509 -text -in servernamecert.pem      <span class="cmt"># View the certificate info</span>
# openssl req -noout -text -in server.csr        <span class="cmt"># View the request info</span>
# openssl s_client -connect cb.vu:443            <span class="cmt"># Check a web server certificate</span>
</pre>
</div>


<div id="cvs"><h1><a>CVS</a></h1>
<p class="xrefp"><a class="xrefp" href="#cvssetup">Server setup</a> | <a class="xrefp" href="#cvstest">CVS test</a> | <a class="xrefp" href="#cvsssh">SSH tunneling</a> | <a class="xrefp" href="#cvsusage">CVS usage</a></p>
<h2 id="cvssetup">Server setup</h2>
<h3>Initiate the CVS</h3>
Decide where the main repository will rest and create a root cvs. For example /usr/local/cvs (as root):
<pre># mkdir -p /usr/local/cvs
# setenv CVSROOT /usr/local/cvs      <span class="cmt"># Set CVSROOT to the new location (local)</span>
# cvs init                           <span class="cmt"># Creates all internal CVS config files</span>
# cd /root
# cvs checkout CVSROOT               <span class="cmt"># Checkout the config files to modify them</span>
# cd CVSROOT
edit config ( fine as it is)
# cvs commit config
cat &gt;&gt; writers                       <span class="cmt"># Create a writers file (optionally also readers)</span>
colin
^D                                   <span class="cmt"># Use [Control][D] to quit the edit</span>
# cvs add writers                    <span class="cmt"># Add the file writers into the repository</span>
# cvs edit checkoutlist
# cat &gt;&gt; checkoutlist
writers
^D                                   <span class="cmt"># Use [Control][D] to quit the edit</span>
# cvs commit                         <span class="cmt"># Commit all the configuration changes</span>
</pre>
Add a <strong>readers</strong> file if you want to differentiate read and write permissions <i>Note:</i> Do not (ever) edit files directly into the main cvs, but rather checkout the file, modify it and check it in. We did this with the file <strong>writers</strong> to define the write access.<br/>
There are three popular ways to access the CVS at this point. The first two don't need any further configuration. See the examples on <a href="#cvsroot">CVSROOT</a> below for how to use them:

<ul>
  <li>Direct local access to the file system. The user(s) need sufficient file permission to access the CS directly and there is no further authentication in addition to the OS login. However this is only useful if the repository is local.</li>
  <li>Remote access with ssh with the ext protocol. Any use with an ssh shell account and read/write permissions on the CVS server can access the CVS directly with ext over ssh without any additional tunnel. There is no server process running on the CVS for this to work. The ssh login does the authentication.</li>
  <li>Remote access with pserver. This is the preferred use for larger user base as the users are authenticated by the CVS pserver with a dedicated password database, there is therefore no need for local users accounts. This setup is explained below.</li>
</ul>

<h3>Network setup with inetd</h3>
The CVS can be run locally only if a network access is not needed. For a remote access, the daemon inetd can start the pserver with the following line in /etc/inetd.conf (/etc/xinetd.d/cvs on SuSE):
<pre>cvspserver	stream  tcp  nowait  cvs  /usr/bin/cvs	cvs \
--allow-root=/usr/local/cvs pserver
</pre>
It is a good idea to block the cvs port from the Internet with the firewall and use an ssh tunnel to access the repository remotely.

<h3>Separate authentication</h3>
It is possible to have cvs users which are not part of the OS (no local users). This is actually probably wanted too from the security point of view. Simply add a file named <strong>passwd</strong> (in the CVSROOT directory) containing the users login and password in the crypt format. This is can be done with the apache htpasswd tool.<br/>
<i>Note:</i> This passwd file is the only file which has to be edited directly in the CVSROOT directory. Also it won't be checked out. More info with htpasswd --help
<pre># htpasswd -cb passwd user1 password1  <span class="cmt"># -c creates the file</span>
# htpasswd -b passwd user2 password2
</pre>

Now add <code>:cvs</code> at the end of each line to tell the cvs server to change the user to cvs (or whatever your cvs server is running under). It looks like this:
<pre># cat passwd
user1:xsFjhU22u8Fuo:cvs
user2:vnefJOsnnvToM:cvs
</pre>

<h2 id="cvstest">Test it</h2>
Test the login as normal user (for example here me)
<pre># cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs login
Logging in to :pserver:colin@192.168.50.254:2401/usr/local/cvs
CVS password:

</pre>

<h3 id="cvsroot">CVSROOT variable</h3>
This is an environment variable used to specify the location of the repository we're doing operations on. For local use, it can be just set to the directory of the repository. For use over the network, the transport protocol must be specified. Set the CVSROOT variable with <code>setenv CVSROOT string</code> on a csh, tcsh shell, or with <code>export CVSROOT=string</code> on a sh, bash shell.
<pre># setenv CVSROOT :pserver:&lt;username&gt;@&lt;host&gt;:/cvsdirectory
<i><span class="cmt">For example:</span></i>
# setenv CVSROOT /usr/local/cvs                               <span class="cmt"># Used locally only</span>
# setenv CVSROOT :local:/usr/local/cvs                        <span class="cmt"># Same as above</span>
# setenv CVSROOT :ext:user@cvsserver:/usr/local/cvs           <span class="cmt"># Direct access with SSH</span>
# setenv CVS_RSH ssh                                          <span class="cmt"># for the ext access</span>
# setenv CVSROOT :pserver:user@cvsserver.254:/usr/local/cvs   <span class="cmt"># network with pserver</span>
</pre>
When the login succeeded one can import a new project into the repository:
<strong>cd into</strong> your project root directory
<pre>cvs import &lt;module name&gt; &lt;vendor tag&gt; &lt;initial tag&gt;
cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs import MyProject MyCompany START
</pre>

Where MyProject is the name of the new project in the repository (used later to checkout). Cvs will import the current directory content into the new project.<br/><br/>
To checkout:
<pre># cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs checkout MyProject
<i><span class="cmt">or</span></i>
# setenv CVSROOT :pserver:colin@192.168.50.254:/usr/local/cvs
# cvs checkout MyProject
</pre>

<h2 id="cvsssh">SSH tunneling for CVS</h2>
We need 2 shells for this. On the first shell we connect to the cvs server with ssh and port-forward the cvs connection. On the second shell we use the cvs normally as if it where running locally.
<br/>
on shell 1:
<pre># ssh -L2401:localhost:2401 colin@cvs_server   <span class="cmt"># Connect directly to the CVS server. Or:</span>
# ssh -L2401:cvs_server:2401 colin@gateway     <span class="cmt"># Use a gateway to reach the CVS</span></pre>
on shell 2:
<pre># setenv CVSROOT :pserver:colin@localhost:/usr/local/cvs
# cvs login
Logging in to :pserver:colin@localhost:2401/usr/local/cvs
CVS password:
# cvs checkout MyProject/src
</pre>
<h2 id="cvsusage">CVS commands and usage</h2>
<h3>Import</h3>
The import command is used to add a whole directory, it must be run from within the directory to be imported. Say the directory /devel/ contains all files and subdirectories to be imported. The directory name on the CVS (the module) will be called "myapp".
<pre># cvs import [options] directory-name vendor-tag release-tag
# cd /devel                          <span class="cmt"># Must be inside the project to import it</span>
# cvs import myapp Company R1_0      <span class="cmt"># Release tag can be anything in one word</span>
</pre>
After a while a new directory "/devel/tools/" was added and it has to be imported too.
<pre># cd /devel/tools
# cvs import myapp/tools Company R1_0
</pre>
<h3>Checkout update add commit</h3>
<pre># cvs co myapp/tools                 <span class="cmt"># Will only checkout the directory tools</span>
# cvs co -r R1_1 myapp               <span class="cmt"># Checkout myapp at release R1_1 (is sticky)</span>
# cvs -q -d update -P                <span class="cmt"># A typical CVS update</span>
# cvs update -A                      <span class="cmt"># Reset any sticky tag (or date, option)</span>
# cvs add newfile                    <span class="cmt"># Add a new file</span>
# cvs add -kb newfile                <span class="cmt"># Add a new binary file</span>
# cvs commit file1 file2             <span class="cmt"># Commit the two files only</span>
# cvs commit -m "message"            <span class="cmt"># Commit all changes done with a message</span>
</pre>

<h3>Create a patch</h3>
It is best to create and apply a patch from the working development directory related to the project, or from within the source directory.
<pre># cd /devel/project
# diff -Naur olddir newdir &gt; patchfile <span class="cmt"># Create a patch from a directory or a file</span>
# diff -Naur oldfile newfile &gt; patchfile
</pre>
<h3>Apply a patch</h3>
Sometimes it is necessary to strip a directory level from the patch, depending how it was created. In case of difficulties, simply look at the first lines of the patch and try -p0, -p1 or -p2.
<pre># cd /devel/project
# patch --dry-run -p0 &lt; patchfile    <span class="cmt"># Test the path without applying it</span>
# patch -p0 &lt; patchfile
# patch -p1 &lt; patchfile              <span class="cmt"># strip off the 1st level from the path</span>
</pre>
</div>

<div id="svn"><h1><a>SVN</a></h1>
<p class="xrefp"><a class="xrefp" href="#svnsetup">Server setup</a> | <a class="xrefp" href="#svnssh">SVN+SSH</a> | <a class="xrefp" href="#svnhttp">SVN over http</a> | <a class="xrefp" href="#svnusage">SVN usage</a></p>
<a href="http://subversion.tigris.org/">Subversion (SVN)</a><span class="fn">http://subversion.tigris.org/</span> is a version control system designed to be the successor of CVS (Concurrent Versions System). The concept is similar to CVS, but many shortcomings where improved. See also the <a href="http://svnbook.red-bean.com/en/1.4/">SVN book</a><span class="fn">http://svnbook.red-bean.com/en/1.4/</span>.
<h2 id="svnsetup">Server setup</h2>
The initiation of the repository is fairly simple (here for example <code>/home/svn/</code> must exist):
<pre># svnadmin create --fs-type fsfs /home/svn/project1</pre>
Now the access to the repository is made possible with:
<ul>
  <li><code>file://</code> Direct file system access with the svn client with. This requires local permissions on the file system.</li>
  <li><code>svn://</code> or <code>svn+ssh://</code> Remote access with the svnserve server (also over SSH). This requires local permissions on the file system.</li>
  <li><code>http://</code> Remote access with webdav using apache. No local users are necessary for this method.</li>
</ul>
Using the local file system, it is now possible to import and then check out an existing project. Unlike with CVS it is not necessary to cd into the project directory, simply give the full path:
<pre># svn import /project1/ file:///home/svn/project1/trunk -m 'Initial import'
# svn checkout file:///home/svn/project1
</pre>
The new directory "trunk" is only a convention, this is not required.
<h3 id="svnssh">Remote access with ssh</h3>
No special setup is required to access the repository via ssh, simply replace <code>file://</code> with <code>svn+ssh/hostname</code>. For example:
<pre># svn checkout svn+ssh://hostname/home/svn/project1</pre>
As with the local file access, every user needs an ssh access to the server (with a local account) and also read/write access. This method might be suitable for a small group. All users could belong to a subversion group which owns the repository, for example:
<pre># groupadd subversion
# groupmod -A user1 subversion
# chown -R root:subversion /home/svn
# chmod -R 770 /home/svn
</pre>
<h3 id="svnhttp">Remote access with http (apache)</h3>
Remote access over http (https) is the only good solution for a larger user group. This method uses the apache authentication, not the local accounts. This is a typical but small apache configuration:
<pre>LoadModule dav_module         modules/mod_dav.so
LoadModule dav_svn_module     modules/mod_dav_svn.so
LoadModule authz_svn_module   modules/mod_authz_svn.so   <span class="cmt"> # Only for access control</span>
</pre><pre style="page-break-inside: avoid;">&lt;Location /svn&gt;
  DAV svn
  <span class="cmt"># any "/svn/foo" URL will map to a repository /home/svn/foo</span>
  SVNParentPath /home/svn
  AuthType Basic
  AuthName "Subversion repository"
  AuthzSVNAccessFile /etc/apache2/svn.acl
  AuthUserFile /etc/apache2/svn-passwd
  Require valid-user
&lt;/Location&gt;
</pre>
The apache server needs full access to the repository:
<pre># chown -R www:www /home/svn</pre>
Create a user with htpasswd2:
<pre># htpasswd -c /etc/svn-passwd user1 <span class="cmt"> # -c creates the file</span></pre>
<h4>Access control svn.acl example</h4>
<pre><span class="cmt"># Default it read access. "* =" would be default no access</span>
[/]
* = r
[groups]
project1-developers = joe, jack, jane
<span class="cmt"># Give write access to the developers</span>
[project1:]
@project1-developers = rw
</pre>

<h2 id="svnusage">SVN commands and usage</h2>
See also the <a rel="nofollow" href="http://www.cs.put.poznan.pl/csobaniec/Papers/svn-refcard.pdf">Subversion Quick Reference Card</a><span class="fn">http://www.cs.put.poznan.pl/csobaniec/Papers/svn-refcard.pdf</span>. <a href="http://tortoisesvn.tigris.org/">Tortoise SVN</a><span class="fn">http://tortoisesvn.tigris.org</span> is a nice Windows interface.
<h3 id="svnimport">Import</h3>
A new project, that is a directory with some files, is imported into the repository with the <code>import</code> command. Import is also used to add a directory with its content to an existing project.
<pre># svn help import                               <span class="cmt"> # Get help for any command</span>
<span class="cmt">    # Add a new directory (with content) into the src dir on project1</span>
# svn import /project1/newdir http://host.url/svn/project1/trunk/src -m 'add newdir'
</pre>
<h3 id="svntypical">Typical SVN commands</h3>
<pre># svn co http://host.url/svn/project1/trunk     <span class="cmt"> # Checkout the most recent version</span>
<span class="cmt">    # Tags and branches are created by copying</span>
# svn mkdir http://host.url/svn/project1/tags/  <span class="cmt"> # Create the tags directory</span>
# svn copy -m "Tag rc1 rel." http://host.url/svn/project1/trunk \
                             http://host.url/svn/project1/tags/1.0rc1
# svn status [--verbose]                        <span class="cmt"> # Check files status into working dir</span>
# svn add src/file.h src/file.cpp               <span class="cmt"> # Add two files</span>
# svn commit -m 'Added new class file'          <span class="cmt"> # Commit the changes with a message</span>
# svn ls http://host.url/svn/project1/tags/     <span class="cmt"> # List all tags</span>
# svn move foo.c bar.c                          <span class="cmt"> # Move (rename) files</span>
# svn delete some_old_file                      <span class="cmt"> # Delete files</span>
</pre>

</div>

<div id="other"><h1><a>Useful Commands</a></h1>
<p class="xrefp"><a class="xrefp" href="#less">less</a> | <a class="xrefp" href="#vi">vi</a> | <a class="xrefp" href="#mail">mail</a> | <a class="xrefp" href="#tar">tar</a> | <a class="xrefp" href="#dd">dd</a> | <a class="xrefp" href="#screen">screen</a> | <a class="xrefp" href="#find">find</a> | <a class="xrefp" href="#misccmd">Miscellaneous</a></p>
<h2 id="less">less</h2>
The <code>less</code> command displays a text document on the console. It is present on most installation.
<pre># less unixtoolbox.xhtml</pre>
Some important commands are (^N stands for [control]-[N]):
<ul style="list-style-type: none;">
  <li><strong>h  H</strong>       good help on display</li>
  <li><strong>f  ^F  ^V  SPACE</strong>       Forward  one window (or N lines).</li>
  <li><strong>b  ^B  ESC-v</strong>       Backward one window (or N lines).</li>
  <li><strong>F</strong>       Forward forever; like "tail -f".</li>
  <li><strong>/pattern</strong>       Search forward for (N-th) matching line.</li>
  <li><strong>?pattern</strong>       Search backward for (N-th) matching line.</li>
  <li><strong>n</strong>       Repeat previous search (for N-th occurrence).</li>
  <li><strong>N</strong>       Repeat previous search in reverse direction.</li>
  <li><strong>q</strong>       quit</li>
</ul>


<h2 id="vi">vi</h2>
Vi is present on ANY Linux/Unix installation (not gentoo?) and it is therefore useful to know some basic commands. There are two modes: command mode and insertion mode. The commands mode is accessed with <strong>[ESC]</strong>, the insertion mode with <strong>i</strong>. Use <code>: help</code> if you are lost.<br/>
The editors <code>nano</code> and <code>pico</code> are usually available too and are easier (IMHO) to use.
<h3>Quit</h3>
<ul style="list-style-type: none;">
  <li><strong>:w</strong> newfilename       save the file to newfilename</li>
  <li><strong>:wq or :x</strong>       save and quit</li>
  <li><strong>:q!</strong>       quit without saving</li>
</ul>
<h3>Search and move</h3>
<ul style="list-style-type: none;">
  <li><strong>/string</strong>       Search forward for string</li>
  <li><strong>?string</strong>       Search back for string</li>
  <li><strong>n</strong>       Search for next instance of string</li>
  <li><strong>N</strong>       Search for previous instance of string</li>
  <li><strong>{</strong>       Move a paragraph back</li>
  <li><strong>}</strong>       Move a paragraph forward</li>
  <li><strong>1G</strong>       Move to the first line of the file</li>
  <li><strong>nG</strong>       Move to the n th line of the file</li>
  <li><strong>G</strong>       Move to the last line of the file</li>
  <li><strong>:%s/OLD/NEW/g</strong>       Search and replace every occurrence</li>
</ul>
<h3>Delete text</h3>
<ul style="list-style-type: none;">
  <li><strong>dd</strong>       delete current line</li>
  <li><strong>D</strong>       Delete to the end of the line</li>
  <li><strong>dw</strong>       Delete word</li>
  <li><strong>x</strong>       Delete character</li>
  <li><strong>u</strong>       Undo last</li>
  <li><strong>U</strong>       Undo all changes to current line</li>
</ul>

<h2 id="mail">mail</h2>
The <code>mail</code> command is a basic application to read and send email, it is usually installed. To send an email simply type "mail user@domain". The first line is the subject, then the mail content. Terminate and send the email with a single dot (.) in a new line. Example:
<pre># mail c@cb.vu
Subject: Your text is full of typos
"For a moment, nothing happened. Then, after a second or so, 
nothing continued to happen."
.
EOT
#
</pre>
This is also working with a pipe:
<pre># echo "This is the mail body" | mail c@cb.vu</pre>
This is also a simple way to test the mail server.

<h2 id="tar">tar</h2>
The command <code>tar</code> (tape archive) creates and extracts archives of file and directories. The archive .tar is uncompressed, a compressed archive has the extension .tgz or .tar.gz (zip) or .tbz (bzip2). Do not use absolute path when creating an archive, you probably want to unpack it somewhere else. Some typical commands are:
<h3>Create</h3>
<pre># cd /
# tar -cf home.tar home/        <span class="cmt"># archive the whole /home directory (c for create)</span>
# tar -czf home.tgz home/       <span class="cmt"># same with zip compression</span>
# tar -cjf home.tbz home/       <span class="cmt"># same with bzip2 compression</span>
</pre>
Only include one (or two) directories from a tree, but keep the relative structure. For example archive /usr/local/etc and /usr/local/www and the first directory in the archive should be local/.
<pre># tar -C /usr -czf local.tgz local/etc local/www
# tar -C /usr -xzf local.tgz    <span class="cmt"># To untar the local dir into /usr</span>
# cd /usr; tar -xzf local.tgz   <span class="cmt"># Is the same as above</span>
</pre>
<h3>Extract</h3>
<pre># tar -tzf home.tgz             <span class="cmt"># look inside the archive without extracting (list)</span>
# tar -xf home.tar              <span class="cmt"># extract the archive here (x for extract)</span>
# tar -xzf home.tgz             <span class="cmt"># same with zip compression</span>
# tar -xjf home.tgz             <span class="cmt"># same with bzip2 compression</span>
# tar -xjf home.tgz home/colin/file.txt    <span class="cmt"># Restore a single file</span>
</pre>
<h3>More advanced</h3>
<pre># tar c dir/ | gzip | ssh user@remote 'dd of=dir.tgz' <span class="cmt"># arch dir/ and store remotely.</span>
# tar cvf - `find . -print` &gt; backup.tar              <span class="cmt"># arch the current directory.</span>
# tar -cf - -C /etc . | tar xpf - -C /backup/etc      <span class="cmt"># Copy directories</span>
# tar -cf - -C /etc . | ssh user@remote tar xpf - -C /backup/etc      <span class="cmt"># Remote copy.</span>
# tar -czf home.tgz --exclude '*.o' --exclude 'tmp/' home/
</pre>
<h2 id="dd">dd</h2>
The program <code>dd</code> (disk dump or destroy disk or see <a href="http://roesler-ac.de/wolfram/acro/credits.htm">the meaning of dd</a>) is used to copy partitions and disks and for other copy tricks. Typical usage:
<pre># dd if=&lt;source&gt; of=&lt;target&gt; bs=&lt;byte size&gt; conv=&lt;conversion&gt;</pre>
Important conv options:
<ul style="list-style-type: none;">
  <li><code>notrunc</code>       do not truncate the output file, all zeros will be written as zeros.</li>
  <li><code>noerror</code>       continue after read errors (e.g. bad blocks)</li>
  <li><code>sync</code>       pad every input block with Nulls to ibs-size</li>
</ul>
The default byte size is 512 (one block). The MBR, where the partiton table is located, is on the first block, the first 63 blocks of a disk are empty. Larger byte sizes are faster to copy but require also more memory.
<h3>Backup and restore</h3>
<pre># dd if=/dev/hda of=/dev/hdc bs=16065b                <span class="cmt"># Copy disk to disk (same size)</span>
# dd if=/dev/sda7 of /home/root.img bs=4096 conv=notrunc,noerror <span class="cmt"># Backup /</span>
# dd if /home/root.img of=/dev/sda7 bs=4096 conv=notrunc,noerror <span class="cmt"># Restore /</span>
# dd bs=1M if=/dev/ad4s3e | gzip -c &gt; ad4s3e.gz                  <span class="cmt"># Zip the backup</span>
# gunzip -dc ad4s3e.gz | dd of=/dev/ad0s3e bs=1M                 <span class="cmt"># Restore the zip</span>
# dd bs=1M if=/dev/ad4s3e | gzip | ssh eedcoba@fry 'dd of=ad4s3e.gz' <span class="cmt"># also remote</span>
# gunzip -dc ad4s3e.gz | ssh eedcoba@host 'dd of=/dev/ad0s3e bs=1M'
# dd if=/dev/ad0 of=/dev/ad2 skip=1 seek=1 bs=4k conv=noerror    <span class="cmt"># Skip MBR</span>
    <span class="cmt"># This is necessary if the destination (ad2) is smaller.</span>
</pre>

<h3>Recover</h3>
The command <code>dd</code> will read <i>every single block</i> of the partiton, even the blocks. In case of problems it is better to use the option <code>conv=sync,noerror</code> so dd will skip the bad block and write zeros at the destination. Accordingly it is important to set the block size equal or smaller than the disk block size. A 1k size seems safe, set it with <code>bs=1k</code>. If a disk has bad sectors and the data should be recovered from a partiton, create an image file with dd, mount the image and copy the content to a new disk. With the option <code>noerror</code>, dd will skip the bad sectors and write zeros instead, thus only the data contained in the bad sectors will be lost.

<pre># dd if=/dev/hda of=/dev/null bs=1m                   <span class="cmt"># Check for bad blocks</span>
# dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc | gzip | ssh \ <span class="cmt"># Send to remote</span>
root@fry 'dd of=hda1.gz bs=1k'
# dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc of=hda1.img    <span class="cmt"># Store into an image</span>
# mount -o loop /hda1.img /mnt                        <span class="cmt"># <a class="xref" href="#createimg">Mount the image</a></span>
# rsync -ax /mnt/ /newdisk/                           <span class="cmt"># Copy on a new disk</span>
# dd if=/dev/hda of=/dev/hda                          <span class="cmt"># Refresh the magnetic state</span>
  <span class="cmt"># The above is useful to refresh a disk. It is perfectly safe, but must be unmounted.</span>
</pre>
<h3>Delete</h3>
<pre># dd if=/dev/zero of=/dev/hdc                         <span class="cmt"># Delete full disk</span>
# dd if=/dev/urandom of=/dev/hdc                      <span class="cmt"># Delete full disk better</span>
# kill -USR1 PID                                      <span class="cmt"># View dd progress (Linux only!)</span>
</pre>
<h3>MBR tricks</h3>
The MBR contains the boot loader and the partition table and is 512 bytes small. The first 446 are for the boot loader, the bytes 446 to 512 are for the partition table.
<pre># dd if=/dev/sda of=/mbr_sda.bak bs=512 count=1       <span class="cmt"># Backup the full MBR</span>
# dd if=/dev/zero of=/dev/sda bs=512 count=1          <span class="cmt"># Delete MBR and partiton table</span>
# dd if=/mbr_sda.bak of=/dev/sda bs=512 count=1       <span class="cmt"># Restore the full MBR</span>
# dd if=/mbr_sda.bak of=/dev/sda bs=446 count=1       <span class="cmt"># Restore only the boot loader</span>
# dd if=/mbr_sda.bak of=/dev/sda bs=1 count=64 skip=446 seek=446 <span class="cmt"># Restore partition table</span>
</pre>

<h2 id="screen">screen</h2>
Screen has two main functionalities:
<ul>
<li>Run multiple terminal session within a single terminal.</li>
<li>A started program is decoupled from the real terminal and can thus run in the background. The real terminal can be closed and reattached later.</li>
</ul>
<h3>Short start example</h3>
start screen with:
<pre># screen</pre>
Within the screen session we can start a long lasting program (like top). Detach the terminal and reattach the same terminal from an other machine (over ssh for example).
<pre># top</pre>
Now detach with <strong>Ctrl-a Ctrl-d</strong>. Reattach the terminal with
<pre># screen -r</pre>
or better:
<pre># screen -R -D</pre>
Attach here and now. In detail this means: If a session is running, then reattach. If  necessary detach and logout remotely first. If it was not running create it and notify the user.

<h3>Screen commands (within screen)</h3>
All screen commands start with <strong>Ctrl-a</strong>.
<ul>
  <li><strong>Ctrl-a ?</strong> help and summary of functions</li>
  <li><strong>Ctrl-a c</strong> create an new window (terminal)</li>
  <li><strong>Ctrl-a Ctrl-n and Ctrl-a Ctrl-p</strong> to switch to the next or previous
window in the list, by number.</li>
  <li><strong>Ctrl-a Ctrl-N</strong> where N is a number from 0 to 9, to switch to the corresponding window.</li>
  <li><strong>Ctrl-a "</strong> to get a navigable list of running windows</li>
  <li><strong>Ctrl-a a</strong> to clear a missed Ctrl-a</li>
  <li><strong>Ctrl-a Ctrl-d</strong> to disconnect and leave the session running in the background</li>
  <li><strong>Ctrl-a x</strong> lock the screen terminal with a password</li>
</ul>
The screen session is terminated when the program within the running terminal is closed and you logout from the terminal.

<h2 id="find">Find</h2>
Some important options:
<ul style="list-style-type: none;">
  <li><code>-x</code> (on BSD) <code>-xdev</code> (on Linux)       Stay on the same file system (dev in fstab).</li>
  <li><code>-exec cmd {} \;</code>       Execute the command and replace {} with the full path</li>
  <li><code>-iname</code>       Like -name but is case insensitive</li>
  <li><code>-ls</code>       Display information about the file (like ls -la)</li>
  <li><code>-size n</code>       n is +-n (k M G T P)</li>
  <li><code>-cmin n</code>       File's status was last changed n minutes ago.</li>
</ul>
<pre># find . -type f ! -perm -444        <span class="cmt"># Find files not readable by all</span>
# find . -type d ! -perm -111        <span class="cmt"># Find dirs not accessible by all</span>
# find /home/user/ -cmin 10 -print   <span class="cmt"># Files created or modified in the last 10 min.</span>
# find . -name '*.[ch]' | xargs grep -E 'expr' <span class="cmt"># Search 'expr' in this dir and below.</span>
# find / -name "*.core" | xargs rm   <span class="cmt"># Find core dumps and delete them (also try core.*)</span>
# find / -name "*.core" -print -exec rm {} \;  <span class="cmt"># Other syntax</span>
      <span class="cmt"># Find images and create an archive, iname is not case sensitive. -r for append</span>
# find . \( -iname "*.png" -o -iname "*.jpg" \) -print -exec tar -rf images.tar {} \;
# find . -type f -name "*.txt" ! -name README.txt -print  <span class="cmt"># Exclude README.txt files</span>
# find /var/ -size +10M -exec ls -lh {} \;     <span class="cmt"># Find large files &gt; 10 MB</span>
# find /var/ -size +10M -ls           <span class="cmt"># This is simpler</span>
# find . -size +10M -size -50M -print
# find /usr/ports/ -name work -type d -print -exec rm -rf {} \;  <span class="cmt"># Clean the ports</span>
      <span class="cmt"># Find files with SUID; those file are vulnerable and must be kept secure</span>
# find / -type f -user root -perm -4000 -exec ls -l {} \; 
</pre>
Be careful with xarg or exec as it might or might not honor quotings and can return wrong results when files or directories contain spaces. In doubt use "-print0 | xargs -0" instead of "| xargs". The option -print0 must be the last in the find command. See this nice <a href="http://www.hccfl.edu/pollock/Unix/FindCmd.htm">mini tutorial for find</a><span class="fn">http://www.hccfl.edu/pollock/Unix/FindCmd.htm</span>.
<pre># find . -type f | xargs ls -l       <span class="cmt"># Will not work with spaces in names</span>
# find . -type f -print0 | xargs -0 ls -l  <span class="cmt"># Will work with spaces in names</span>
# find . -type f -exec ls -l '{}' \; <span class="cmt"># Or use quotes '{}' with -exec</span>
</pre>
<h2 id="misccmd">Miscellaneous</h2>
<pre># which command                      <span class="cmt"># Show full path name of command</span>
# time command                       <span class="cmt"># See how long a command takes to execute</span>
# time cat                           <span class="cmt"># Use time as stopwatch. Ctrl-c to stop</span>
# set | grep $USER                   <span class="cmt"># List the current environment</span>
# cal -3                             <span class="cmt"># Display a three month calendar</span>
# date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
# date 10022155                      <span class="cmt"># Set date and time</span>
# whatis grep                        <span class="cmt"># Display a short info on the command or word</span>
# whereis java                       <span class="cmt"># Search path and standard directories for word</span>
# setenv varname value               <span class="cmt"># Set env. variable varname to value (csh/tcsh)</span>
# export varname="value"             <span class="cmt"># set env. variable varname to value (sh/ksh/bash)</span>
# pwd                                <span class="cmt"># Print working directory</span>
# mkdir -p /path/to/dir              <span class="cmt"># no error if existing, make parent dirs as needed</span>
# mkdir -p project/{bin,src,obj,doc/{html,man,pdf},debug/some/more/dirs}
# rmdir /path/to/dir                 <span class="cmt"># Remove directory</span>
# rm -rf /path/to/dir                <span class="cmt"># Remove directory and its content (force)</span>
# cp -la /dir1 /dir2                 <span class="cmt"># Archive and hard link files instead of copy</span>
# cp -lpR /dir1 /dir2                <span class="cmt"># Same for FreeBSD</span>
# cp unixtoolbox.xhtml{,.bak}        <span class="cmt"># Short way to copy the file with a new extension</span>
# mv /dir1 /dir2                     <span class="cmt"># Rename a directory</span>
</pre>
</div>

<div id="software"><h1><a>Install Software</a></h1>
<h2 id="softwarelist">List installed packages</h2>
<pre># rpm -qa                            <span class="cmt"># List installed packages (RH, SuSE, RPM based)</span>
# dpkg -l                            <span class="cmt"># Debian, Ubuntu</span>
# pkg_info                           <span class="cmt"># FreeBSD list all installed packages</span>
# pkg_info -W smbd                   <span class="cmt"># FreeBSD show which package smbd belongs to</span>
# pkginfo                            <span class="cmt"># Solaris</span>
</pre>
<h2 id="softwareadd">Add/remove software</h2>
Front ends: yast2/yast for SuSE, redhat-config-packages for Red Hat.
<pre># rpm -i pkgname.rpm                 <span class="cmt"># install the package (RH, SuSE, RPM based)</span>
# rpm -e pkgname                     <span class="cmt"># Remove package</span>
</pre>
<h3>Debian</h3>
<pre># apt-get update                     <span class="cmt"># First update the package lists</span>
# apt-get install emacs              <span class="cmt"># Install the package emacs</span>
# dpkg --remove emacs                <span class="cmt"># Remove the package emacs</span>
# dpkg -S file                       <span class="cmt"># find what package a file belongs to</span>
</pre>
<h3>Gentoo</h3>
Gentoo uses emerge as the heart of its "Portage" package management system.
<pre># emerge --sync                      <span class="cmt"># First sync the local portage tree</span>
# emerge -u packagename              <span class="cmt"># Install or upgrade a package</span>
# emerge -C packagename              <span class="cmt"># Remove the package</span>
# revdep-rebuild                     <span class="cmt"># Repair dependencies</span>
</pre>
<h3>Solaris</h3>
The &lt;cdrom&gt; path is usually <code>/cdrom/cdrom0</code>.
<pre># pkgadd -d &lt;cdrom&gt;/Solaris_9/Product SUNWgtar
# pkgadd -d SUNWgtar                 <span class="cmt"># Add downloaded package (bunzip2 first)</span>
# pkgrm SUNWgtar                     <span class="cmt"># Remove the package</span>
</pre>
<h3>FreeBSD</h3>
<pre># pkg_add -r rsync                   <span class="cmt"># Fetch and install rsync.</span>
# pkg_delete /var/db/pkg/rsync-xx    <span class="cmt"># Delete the rsync package</span>
</pre>
Set where the packages are fetched from with the <code>PACKAGESITE</code> variable. For example:
<pre># export PACKAGESITE=ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages/Latest/ 
# or ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-6-stable/Latest/
</pre>
<h3>FreeBSD ports</h3>
The port tree <code>/usr/ports/</code> is a collection of software ready to compile and install. The ports are updated with the program <code>portsnap</code>.
<pre># portsnap fetch extract             <span class="cmt"># Create the tree when running the first time</span>
# portsnap fetch update              <span class="cmt"># Update the port tree</span>
# cd /usr/ports/net/rsync/           <span class="cmt"># Select the package to install</span>
# make install distclean             <span class="cmt"># Install and cleanup (also see man ports)</span>
# make package                       <span class="cmt"># Make a binary package for the port</span>
</pre>

<h2 id="librarypath">Library path</h2>
Due to complex dependencies and runtime linking, programs are difficult to copy to an other system or distribution. However for small programs with little dependencies, the missing libraries can be copied over. The runtime libraries (and the missing one) are checked with <code>ldd</code> and managed with <code>ldconfig</code>.
<pre># ldd /usr/bin/rsync                 <span class="cmt"># List all needed runtime libraries</span>
# ldconfig -n /path/to/libs/         <span class="cmt"># Add a path to the shared libraries directories</span>
# ldconfig -m /path/to/libs/         <span class="cmt"># FreeBSD</span>
# LD_LIBRARY_PATH                    <span class="cmt"># The variable set the link library path</span>
</pre>
</div>

<div id="convert"><h1><a>Convert Media</a></h1>
Sometimes one simply need to convert a video, audio file or document to another format.
<h2 id="encoding">Text encoding</h2>
Text encoding can get totally wrong, specially when the language requires
special characters like àäç. The command <code>iconv</code> can convert from
one encoding to an other.
<pre># iconv -f &lt;from_encoding&gt; -t &lt;to_encoding&gt; &lt;input_file&gt;
# iconv -f ISO8859-1 -t UTF-8 -o file.input &gt; file_utf8
# iconv -l                           <span class="cmt"># List known coded character sets</span>
</pre>
Without the -f option, iconv will use the local char-set, which is usually fine
if the document displays well.
<h2 id="newlines">Unix - DOS newlines</h2>
Convert DOS (CR/LF) to Unix (LF) newlines within a Unix shell. See also <code>dos2unix</code> and <code>unix2dos</code> if you have them.
<pre># sed 's/.$//' dosfile.txt &gt; unixfile.txt
</pre>
Convert Unix to DOS newlines within a Windows environment. Use sed from mingw or cygwin.
<pre># sed -n p unixfile.txt &gt; dosfile.txt
</pre>

<h2>PDF to Jpeg and concatenate PDF files</h2>
Convert a PDF document with <code>gs</code> (GhostScript) to jpeg (or png) images for each page. Also much shorter with <code>convert</code> (from ImageMagick or GraphicsMagick).
<pre># gs -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 \
 -dMaxStripSize=8192 -sOutputFile=unixtoolbox_%d.jpg unixtoolbox.pdf
# convert unixtoolbox.pdf unixtoolbox-%03d.png
# convert *.jpeg images.pdf          <span class="cmt"># Create a simple PDF with all pictures</span>
</pre>
Ghostscript can also concatenate multiple pdf files into a single one. This only works well if the PDF files are "well behaved".
<pre># gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=all.pdf \
file1.pdf file2.pdf ...              <span class="cmt"># On Windows use '#' instead of '='</span>
</pre>

<h2>Convert video</h2>
Compress the Canon digicam video with an mpeg4 codec and repair the crappy sound.
<pre># mencoder -o videoout.avi -oac mp3lame -ovc lavc -srate 11025 \
-channels 1 -af-adv force=1 -lameopts preset=medium -lavcopts \
vcodec=msmpeg4v2:vbitrate=600 -mc 0 vidoein.AVI
</pre>
See <a href="http://sox.sourceforge.net/">sox</a> for sound processing.

<h2>Copy an audio cd</h2>
The program <a rel="nofollow" href="http://xiph.org/paranoia/"><code>cdparanoia</code></a><span class="fn">http://xiph.org/paranoia/</span> can save the audio tracks (FreeBSD port in audio/cdparanoia/), <code>oggenc</code> can encode in Ogg Vorbis format, <code>lame</code> converts to mp3.
<pre># cdparanoia -B                      <span class="cmt"># Copy the tracks to wav files in current dir</span>
# lame -b 256 in.wav out.mp3         <span class="cmt"># Encode in mp3 256 kb/s</span>
# for i in *.wav; do lame -b 256 $i `basename $i .wav`.mp3; done
# oggenc in.wav -b 256 out.ogg       <span class="cmt"># Encode in Ogg Vorbis 256 kb/s</span>
</pre>
</div>

<div id="printing"><h1><a>Printing</a></h1>
<h2>Print with lpr</h2>
<pre style="page-break-inside: avoid;"># lpr unixtoolbox.ps                 <span class="cmt"># Print on default printer</span>
# export PRINTER=hp4600              <span class="cmt"># Change the default printer</span>
# lpr -Php4500 #2 unixtoolbox.ps     <span class="cmt"># Use printer hp4500 and print 2 copies</span>
# lpr -o Duplex=DuplexNoTumble ...   <span class="cmt"># Print duplex along the long side</span>
# lpr -o PageSize=A4,Duplex=DuplexNoTumble ...
# lpq                                <span class="cmt"># Check the queue on default printer</span>
# lpq -l -Php4500                    <span class="cmt"># Queue on printer hp4500 with verbose</span>
# lprm -                             <span class="cmt"># Remove all users jobs on default printer</span>
# lprm -Php4500 3186                 <span class="cmt"># Remove job 3186. Find job nbr with lpq</span>
# lpc status                         <span class="cmt"># List all available printers</span>
# lpc status hp4500                  <span class="cmt"># Check if printer is online and queue length</span>
</pre>
Some devices are not postscript and will print garbage when fed with a pdf file. This might be solved with:
<pre># gs -dSAFER -dNOPAUSE -sDEVICE=deskjet -sOutputFile=\|lpr file.pdf</pre>
</div>

<div id="databases"><h1><a>Databases</a></h1>
<h2 id="pgsql">PostgreSQL</h2>
<h3>Change root or a username password</h3>
<pre># psql -d template1 -U pgsql
&gt; alter user pgsql with password 'pgsql_password';  <span class="cmt"># Use username instead of "pgsql"</span>
</pre>
<h3>Create user and database</h3>
The commands <code>createuser</code>, <code>dropuser</code>, <code>createdb</code> and <code>dropdb</code> are convenient shortcuts equivalent to the SQL commands. The new user is bob with database bobdb ; use as root with pgsql the database super user:
<pre># createuser -U pgsql -P bob         <span class="cmt"># -P will ask for password</span>
# createdb -U pgsql -O bob bobdb     <span class="cmt"># new bobdb is owned by bob</span>
# dropdb bobdb                       <span class="cmt"># Delete database bobdb</span>
# dropuser bob                       <span class="cmt"># Delete user bob</span>
</pre>
The general database authentication mechanism is configured in pg_hba.conf
<h3>Grant remote access</h3>
The file <code>$PGSQL_DATA_D/postgresql.conf</code> specifies the address to bind to. Typically <code>listen_addresses = '*'</code> for Postgres 8.x.<br/>
The file <code>$PGSQL_DATA_D/pg_hba.conf</code> defines the access control. Examples:
<pre># TYPE  DATABASE    USER        IP-ADDRESS        IP-MASK          METHOD
host    bobdb       bob        212.117.81.42     255.255.255.255   password
host    all         all        0.0.0.0/0                           password
</pre>
<h3>Backup and restore</h3>
The backups and restore are done with the user pgsql or postgres. Backup and restore a single database:
<pre># pg_dump --clean dbname &gt; dbname_sql.dump
# psql dbname &lt; dbname_sql.dump
</pre>
Backup and restore all databases (including users):
<pre># pg_dumpall --clean &gt; full.dump
# psql -f full.dump postgres
</pre>
In this case the restore is started with the database postgres which is better when reloading an empty cluster.

<h2 id="mysql">MySQL</h2>
<h3>Change mysql root or username password</h3>
<h4>Method 1</h4>
<pre># /etc/init.d/mysql stop
<i><span class="cmt">or</span></i>
# killall mysqld
# mysqld --skip-grant-tables
# mysqladmin -u root password 'newpasswd'
# /etc/init.d/mysql start
</pre>
<h4>Method 2</h4>
<pre># mysql -u root mysql
<span class="cmt">mysql&gt;</span> UPDATE USER SET PASSWORD=PASSWORD("newpassword") where user='root';
<span class="cmt">mysql&gt;</span> FLUSH PRIVILEGES;                           <span class="cmt"># Use username instead of "root"</span>
<span class="cmt">mysql&gt;</span> quit
</pre>
<h3>Create user and database</h3>
<pre># mysql -u root mysql
<span class="cmt">mysql&gt;</span> CREATE DATABASE bobdb;
<span class="cmt">mysql&gt;</span> GRANT ALL ON *.* TO 'bob'@'%' IDENTIFIED BY 'pwd'; <span class="cmt"># Use localhost instead of %</span>
                                                   <span class="cmt"># to restrict the network access</span>
<span class="cmt">mysql&gt;</span> DROP DATABASE bobdb;                        <span class="cmt"># Delete database</span>
<span class="cmt">mysql&gt;</span> DROP USER bob;                              <span class="cmt"># Delete user</span>
<span class="cmt">mysql&gt;</span> DELETE FROM mysql.user WHERE user='bob and host='hostname'; <span class="cmt"># Alt. command</span>
<span class="cmt">mysql&gt;</span> FLUSH PRIVILEGES;
</pre>
<h3>Grant remote access</h3>
Remote access is typically permitted for a database, and not all databases. The file <code>/etc/my.cnf</code> contains the IP address to bind to. Typically comment the line <code>bind-address =</code> out.
<pre># mysql -u root mysql
<span class="cmt">mysql&gt;</span> GRANT ALL ON bobdb.* TO bob@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
<span class="cmt">mysql&gt;</span> REVOKE GRANT OPTION ON foo.* FROM bar@'xxx.xxx.xxx.xxx';
<span class="cmt">mysql&gt;</span> FLUSH PRIVILEGES;                  <span class="cmt"># Use 'hostname' or also '%' for full access</span>
</pre>
<h3>Backup and restore</h3>
Backup and restore a single database:
<pre># mysqldump -u root -psecret --add-drop-database dbname &gt; dbname_sql.dump
# mysql -u root -psecret -D dbname &lt; dbname_sql.dump
</pre>
Backup and restore all databases:
<pre># mysqldump -u root -psecret --add-drop-database --all-databases &gt; full.dump
# mysql -u root -psecret &lt; full.dump
</pre>
Here is "secret" the mysql root password, there is no space after -p. When the -p option is used alone (w/o password), the password is asked at the command prompt.

<h2 id="sqlite">SQLite</h2>
<a href="http://www.sqlite.org/">SQLite</a><span class="fn">http://www.sqlite.org</span> is a small powerfull self-contined, serverless, zero-configuration SQL database.
<h3>Dump and restore</h3>
It can be useful to dump and restore an SQLite database. For example you can edit the dump file to change a column attribute or type and then restore the database. This is easier than messing with SQL commands. Use the command <code>sqlite3</code> for a 3.x database.
<pre># sqlite database.db .dump &gt; dump.sql              <span class="cmt"># dump</span>
# sqlite database.db &lt; dump.sql                    <span class="cmt"># restore</span>
</pre>
<h3>Convert 2.x to 3.x database</h3>
<pre>sqlite database_v2.db .dump | sqlite3 database_v3.db</pre>
</div>

<div id="quota"><h1><a>Disk Quota</a></h1>
A disk quota allows to limit the amount of disk space and/or the number of files a user or (or member of group) can use. The quotas are allocated on a per-file system basis and are enforced by the kernel.
<h2>Linux setup</h2>
The quota tools package usually needs to be installed, it contains the command line tools.<br/>
Activate the user quota in the fstab and remount the partition. If the partition is busy, either all locked files must be closed, or the system must be rebooted. Add <code>usrquota</code> to the fstab mount options, for example:
<pre>/dev/sda2     /home    reiserfs     rw,acl,user_xattr,usrquota 1 1
# mount -o remount /home
# mount                              <span class="cmt"># Check if usrquota is active, otherwise reboot</span>
</pre>
Initialize the quota.user file with <code>quotacheck</code>.
<pre># quotacheck -vum /home
# chmod 644 /home/aquota.user        <span class="cmt"># To let the users check their own quota</span>
</pre>
Activate the quota either with the provided script (e.g. /etc/init.d/quotad on SuSE) or with <code>quotaon</code>:
<pre>quotaon -vu /home</pre>
Check that the quota is active with:
<pre>quota -v</pre>

<h2>FreeBSD setup</h2>
The quota tools are part of the base system, however the kernel needs the option quota. If it is not there, add it and <a href="#compilekernel">recompile</a> the kernel.
<pre>options QUOTA</pre>
As with Linux, add the quota to the fstab options (userquota, not usrquota):
<pre>/dev/ad0s1d    /home    ufs     rw,noatime,userquota    2  2
# mount /home                        <span class="cmt"># To remount the partition</span>
</pre>
Enable disk quotas in /etc/rc.conf and start the quota.
<pre># grep quotas /etc/rc.conf
enable_quotas="YES"                  <span class="cmt"># turn on quotas on startup (or NO).</span>
check_quotas="YES"                   <span class="cmt"># Check quotas on startup (or NO).</span>
# /etc/rc.d/quota start
</pre>

<h2 id="assignquota">Assign quota limits</h2>
The quotas are not limited per default (set to 0). The limits are set with <code>edquota</code> for single users. A quota can be also duplicated to many users. The file structure is different between the quota implementations, but the principle is the same: the values of blocks and inodes can be limited. <i>Only change the values of soft and hard</i>. If not specified, the blocks are 1k. The grace period is set with <code>edquota -t</code>. For example:
<pre># edquota -u colin</pre>
<h3>Linux</h3>
<pre>Disk quotas for user colin (uid 1007):
  Filesystem         blocks       soft       hard     inodes     soft     hard
  /dev/sda8            108       1000       2000          1        0        0
</pre>
<h3>FreeBSD</h3>
<pre>Quotas for user colin:
/home: kbytes in use: 504184, limits (soft = 700000, hard = 800000)
   inodes in use: 1792, limits (soft = 0, hard = 0)
</pre>
<h3>For many users</h3>
The command <code>edquota -p</code> is used to duplicate a quota to other users. For example to duplicate a reference quota to all users:
<pre># edquota -p refuser `awk -F: '$3 &gt; 499 {print $1}' /etc/passwd`
# edquota -p refuser user1 user2     <span class="cmt"># Duplicate to 2 users</span>
</pre>
<h3>Checks</h3>
Users can check their quota by simply typing <code>quota</code> (the file quota.user must be readable). Root can check all quotas.
<pre># quota -u colin                     <span class="cmt"># Check quota for a user</span>
# repquota /home                     <span class="cmt"># Full report for the partition for all users</span>
</pre>
</div>

<div id="shells"><h1><a>Shells</a></h1>
Most Linux distributions use the bash shell while the BSDs use tcsh, the bourne shell is only used for scripts. Filters are very useful and can be piped:
<ul style="list-style-type: none;">
  <li><code>grep</code>   Pattern matching</li>
  <li><code>sed</code>   Search and Replace strings or characters</li>
  <li><code>cut</code>   Print specific columns from a marker</li>
  <li><code>sort</code>   Sort alphabetically or numerically</li>
  <li><code>uniq</code>   Remove duplicate lines from a file</li>
</ul>
For example used all at once:
<pre># ifconfig | sed 's/  / /g' | cut -d" " -f1 | uniq | grep -E "[a-z0-9]+" | sort -r
# ifconfig | sed '/.*inet addr:/!d;s///;s/ .*//'|sort -t. -k1,1n -k2,2n -k3,3n -k4,4n
</pre>
The first character in the sed pattern is a tab. To write a tab on the console, use ctrl-v ctrl-tab.

<h2 id="bash">bash</h2>
Redirects and pipes for bash and sh:
<pre># cmd 1&gt; file                         <span class="cmt"># Redirect stdout to file.</span>
# cmd 2&gt; file                         <span class="cmt"># Redirect stderr to file.</span>
# cmd 1&gt;&gt; file                        <span class="cmt"># Redirect and append stdout to file.</span>
# cmd &amp;&gt; file                         <span class="cmt"># Redirect both stdout and stderr to file.</span>
# cmd &gt;file 2&gt;&amp;1                      <span class="cmt"># Redirects stderr to stdout and then to file.</span>
# cmd1 | cmd2                         <span class="cmt"># pipe stdout to cmd2</span>
# cmd1 2&gt;&amp;1 | cmd2                    <span class="cmt"># pipe stdout and stderr to cmd2</span>
</pre>
Modify your configuration in ~/.bashrc (it can also be ~/.bash_profile). The following entries are useful, reload with ". .bashrc".
<pre style="page-break-inside: avoid;"># in .bashrc
bind '"\e[A"':history-search-backward <span class="cmt"># Use up and down arrow to search</span>
bind '"\e[B"':history-search-forward  <span class="cmt"># the history. Invaluable!</span>
set -o emacs                          <span class="cmt"># Set emacs mode in bash (see below)</span>
set bell-style visible                <span class="cmt"># Do not beep, inverse colors</span>
    <span class="cmt"># Set a nice prompt like [user@host]/path/todir&gt;</span>
PS1="\[\033[1;30m\][\[\033[1;34m\]\u\[\033[1;30m\]"
PS1="$PS1@\[\033[0;33m\]\h\[\033[1;30m\]]\[\033[0;37m\]"
PS1="$PS1\w\[\033[1;30m\]&gt;\[\033[0m\]"
</pre><pre><span class="cmt"># To check the currently active aliases, simply type alias</span>
alias  ls='ls -aF'                    <span class="cmt"># Append indicator (one of */=&gt;@|)</span>
alias  ll='ls -aFls'                  <span class="cmt"># Listing</span>
alias  la='ls -all'
alias ..='cd ..'
alias ...='cd ../..'
export HISTFILESIZE=5000              <span class="cmt"># Larger history</span>
export CLICOLOR=1                     <span class="cmt"># Use colors (if possible)</span>
export LSCOLORS=ExGxFxdxCxDxDxBxBxExEx
</pre>

<h2 id="tcsh">tcsh</h2>
Redirects and pipes for tcsh and csh (simple &gt; and &gt;&gt; are the same as sh):
<pre># cmd &gt;&amp; file                         <span class="cmt"># Redirect both stdout and stderr to file.</span>
# cmd &gt;&gt;&amp; file                        <span class="cmt"># Append both stdout and stderr to file.</span>
# cmd1 | cmd2                         <span class="cmt"># pipe stdout to cmd2</span>
# cmd1 |&amp; cmd2                        <span class="cmt"># pipe stdout and stderr to cmd2</span>
</pre>

The settings for csh/tcsh are set in <code>~/.cshrc</code>, reload with "source .cshrc". Examples:
<pre style="page-break-inside: avoid;"># in .cshrc
alias  ls      'ls -aF'
alias  ll      'ls -aFls'
alias  la      'ls -all'
alias  ..      'cd ..'
alias  ...     'cd ../..'
set   prompt    = "%B%n%b@%B%m%b%/&gt; " <span class="cmt"># like user@host/path/todir&gt;</span>
set   history   =  5000
set   savehist  = ( 6000 merge )
set   autolist                        <span class="cmt"># Report possible completions with tab</span>
set   visiblebell                     <span class="cmt"># Do not beep, inverse colors</span>
</pre><pre><span class="cmt"># Bindkey and colors</span>
bindkey -e     Select Emacs bindings  <span class="cmt"># Use emacs keys to edit the command prompt</span>
bindkey -k up history-search-backward <span class="cmt"># Use up and down arrow to search</span>
bindkey -k down history-search-forward
setenv CLICOLOR 1                     <span class="cmt"># Use colors (if possible)</span>
setenv LSCOLORS ExGxFxdxCxDxDxBxBxExEx
</pre>
The emacs mode enables to use the emacs keys shortcuts to modify the command prompt line. This is extremely useful (not only for emacs users). The most used commands are:
<ul style="list-style-type: none;">
  <li>C-a       Move cursor to beginning of line</li>
  <li>C-e       Move cursor to end of line</li>
  <li>M-b       Move cursor back one word</li>
  <li>M-f       Move cursor forward one word</li>
  <li>M-d       Cut the next word</li>
  <li>C-w       Cut the last word</li>
  <li>C-u       Cut everything before the cursor</li> 
  <li>C-k       Cut everything after the cursor (rest of the line)</li>
  <li>C-y       Paste the last thing to be cut (simply paste)</li>
  <li>C-_       Undo</li>
</ul>
<i>Note:</i> C- = hold control, M- = hold meta (which is usually the alt or escape key).
</div>

<div id="scripting"><h1><a>Scripting</a></h1>
<p class="xrefp"><a class="xrefp" href="#bournebasics">Basics</a> | <a class="xrefp" href="#bourneexample">Script example</a> | <a class="xrefp" href="#sed">sed</a> | <a class="xrefp" href="#regex">Regular Expressions</a> | <a class="xrefp" href="#shcmd">useful commands</a></p>
The Bourne shell (/bin/sh) is present on all Unix installations and scripts written in this language are (quite) portable; <code>man 1 sh</code> is a good reference.

<h2 id="bournebasics">Basics</h2>
<h3>Variables and arguments</h3>
Assign with variable=value and get content with $variable
<pre>MESSAGE="Hello World"                        <span class="cmt"># Assign a string</span>
PI=3.1415                                    <span class="cmt"># Assign a decimal number</span>
N=8
TWON=`expr $N * 2`                           <span class="cmt"># Arithmetic expression (only integers)</span>
TWON=$(($N * 2))                             <span class="cmt"># Other syntax</span>
TWOPI=`echo "$PI * 2" | bc -l`               <span class="cmt"># Use bc for floating point operations</span>
ZERO=`echo "c($PI/4)-sqrt(2)/2" | bc -l`
</pre>
The command line arguments are
<pre>$0, $1, $2, ...                              <span class="cmt"># $0 is the command itself</span> 
$#                                           <span class="cmt"># The number of arguments</span>
$*                                           <span class="cmt"># All arguments (also $@)</span>
</pre>
<h3>Special Variables</h3>
<pre>$$                                           <span class="cmt"># The current process ID</span>
$?                                           <span class="cmt"># exit status of last command</span>
  command
  <span class="keyword">if</span> [ $<span class="pp">?</span> != 0 ]; <span class="keyword">then</span>
    echo "command failed"
  <span class="keyword">fi</span>
<span class="pp">mypath</span>=`pwd`
<span class="pp">mypath</span>=${<span class="pp">mypath</span>}/file.txt
echo ${<span class="pp">mypath</span>##*/}                           <span class="cmt"># Display the filename only</span>
echo ${<span class="pp">mypath</span>%%.*}                           <span class="cmt"># Full path without extention</span>
<span class="pp">var2</span>=${<span class="pp">var</span>:=string}                          <span class="cmt"># Use var if set, otherwise use string
                                             # assign string to var and then to var2.</span>
</pre>

<h3>Constructs</h3>
<pre><span class="keyword">for</span> <span class="pp">file</span> in `ls`
<span class="keyword">do</span>
    echo $<span class="pp">file</span>
<span class="keyword">done</span>

<span class="pp">count</span>=0
<span class="keyword">while</span> [ $<span class="pp">count</span> -lt 5 ]; <span class="keyword">do</span>
    echo $<span class="pp">count</span>
    sleep 1
    <span class="pp">count</span>=$(($<span class="pp">count</span> + 1))
<span class="keyword">done</span>

myfunction() {
    find . -type f -name "*.$<span class="pp">1</span>" -print       <span class="cmt"># $1 is first argument of the function</span>
}
myfunction "txt"
</pre>
<h4>Generate a file</h4>
<pre><span class="pp">MYHOME</span>=/home/colin
cat &gt; testhome.sh &lt;&lt; _EOF
<span class="cmt"># All of this goes into the file testhome.sh</span>
<span class="keyword">if</span> [ -d "$<span class="pp">MYHOME</span>" ] ; <span class="keyword">then</span>
    echo $<span class="pp">MYHOME</span> exists
<span class="keyword">else</span>
    echo $<span class="pp">MYHOME</span> does not exist
<span class="keyword">fi</span>
_EOF
sh testhome.sh
</pre>
<h2 id="bourneexample">Bourne script example</h2>
As a small example, the script used to create a PDF booklet from this xhtml document:
<pre style="page-break-inside: avoid;"><span class="pp">#!/bin/sh</span>
<span class="cmt"># This script creates a book in pdf format ready to print on a duplex printer</span>
<span class="keyword">if</span> [ $<span class="pp">#</span> <span class="keyword">-ne</span> 1 ]; <span class="keyword">then</span>                        <span class="cmt"># Check the argument</span>
  echo 1&gt;&amp;2 "Usage: $0 HtmlFile"
  <span class="keyword">exit</span> 1                                     <span class="cmt"># non zero exit if error</span>
<span class="keyword">fi</span>

<span class="pp">file</span>=$<span class="pp">1</span>                                      <span class="cmt"># Assign the filename</span>
<span class="pp">fname</span>=${<span class="pp">file</span>%.*}                             <span class="cmt"># Get the name of the file only</span>
<span class="pp">fext</span>=${<span class="pp">file</span>#*.}                              <span class="cmt"># Get the extension of the file</span>

prince $<span class="pp">file</span> -o $<span class="pp">fname</span>.pdf                   <span class="cmt"># from www.princexml.com</span>
pdftops -paper A4 -noshrink $<span class="pp">fname</span>.pdf $<span class="pp">fname</span>.ps <span class="cmt"># create postscript booklet</span>
cat $<span class="pp">fname</span>.ps |psbook|psnup -Pa4 -2 |pstops -b "2:0,1U(21cm,29.7cm)" &gt; $<span class="pp">fname</span>.book.ps

ps2pdf13 -sPAPERSIZE=a4 -sAutoRotatePages=None $<span class="pp">fname</span>.book.ps $<span class="pp">fname</span>.book.pdf
                                             <span class="cmt"># use #a4 and #None on Windows!</span>
<span class="keyword">exit</span> 0                                       <span class="cmt"># exit 0 means successful</span>
</pre>

<h2 id="sed">Some sed commands</h2>
Here is <a href="http://student.northpark.edu/pemente/sed/sed1line.txt">the one liner gold mine</a><span class="fn">http://student.northpark.edu/pemente/sed/sed1line.txt</span>. And a good <a href="http://www.grymoire.com/Unix/Sed.html">introduction and tutorial to sed</a><span class="fn">http://www.grymoire.com/Unix/Sed.html</span>.
<pre>sed 's/string1/string2/g'                    <span class="cmt"># Replace string1 with string2</span>
sed -i 's/wroong/wrong/g' *.txt              <span class="cmt"># Replace a recurring word with g</span>
sed 's/\(.*\)1/\12/g'                        <span class="cmt"># Modify anystring1 to anystring2</span>
sed '/&lt;p&gt;/,/&lt;\/p&gt;/d' t.xhtml                 <span class="cmt"># Delete lines that start with &lt;p&gt;</span>
                                             <span class="cmt"># and end with &lt;/p&gt;</span>
sed '/ *#/d; /^ *$/d'                        <span class="cmt"># Remove comments and blank lines</span>
sed 's/[ \t]*$//'                            <span class="cmt"># Remove trailing spaces (use tab as \t)</span>
sed 's/^[ \t]*//;s/[ \t]*$//'                <span class="cmt"># Remove leading and trailing spaces</span>
sed 's/[^*]/[&amp;]/'                            <span class="cmt"># Enclose first char with [] top-&gt;[t]op</span>
sed = file | sed 'N;s/\n/\t/' &gt; file.num     <span class="cmt"># Number lines on a file</span>
</pre>

<h2 id="regex">Regular Expressions</h2>
Some basic regular expression useful for sed too. See <a href="http://www.regular-expressions.info/reference.html">Basic Regex Syntax</a><span class="fn">http://www.regular-expressions.info/reference.html</span> for a good primer.
<pre>[\^$.|?*+()                          <span class="cmt"># special characters any other will match themselves</span>
\                                    <span class="cmt"># escapes special characters and treat as literal</span>
*                                    <span class="cmt"># repeat the previous item zero or more times</span>
.                                    <span class="cmt"># single character except line break characters</span>
.*                                   <span class="cmt"># match zero or more characters</span>
^                                    <span class="cmt"># match at the start of a line/string</span>
$                                    <span class="cmt"># match at the end of a line/string</span>
.$                                   <span class="cmt"># match a single character at the end of line/string</span>
^ $                                  <span class="cmt"># match line with a single space</span>
[^A-Z]                               <span class="cmt"># match any line beginning with any char from A to Z</span>
</pre>

<h2 id="shcmd">Some useful commands</h2>
The following commands are useful to include in a script or as one liners.
<pre>sort -t. -k1,1n -k2,2n -k3,3n -k4,4n         <span class="cmt"># Sort IPv4 ip addresses</span>
echo 'Test' | tr '[:lower:]' '[:upper:]'     <span class="cmt"># Case conversion</span>
echo foo.bar | cut -d . -f 1                 <span class="cmt"># Returns foo</span>
PID=$(ps | grep script.sh | grep bin | awk '{print $1}')    <span class="cmt"># PID of a running script</span>
PID=$(ps axww | grep [p]ing | awk '{print $1}')             <span class="cmt"># PID of ping (w/o grep pid)</span>
IP=$(ifconfig $INTERFACE | sed '/.*inet addr:/!d;s///;s/ .*//')   <span class="cmt"># Linux</span>
IP=$(ifconfig $INTERFACE | sed '/.*inet /!d;s///;s/ .*//')        <span class="cmt"># FreeBSD</span>
if [ `diff file1 file2 | wc -l` != 0 ]; then [...] fi       <span class="cmt"># File changed?</span>
cat /etc/master.passwd | grep -v root | grep -v \*: | awk -F":" \ <span class="cmt"># Create http passwd</span>
'{ printf("%s:%s\n", $1, $2) }' &gt; /usr/local/etc/apache2/passwd

testuser=$(cat /usr/local/etc/apache2/passwd | grep -v \    <span class="cmt"># Check user in passwd</span>
root | grep -v \*: | awk -F":" '{ printf("%s\n", $1) }' | grep ^user$)
:(){ :|:&amp; };:                                <span class="cmt"># bash fork bomb. Will kill your machine</span>
tail +2 file &gt; file2                         <span class="cmt"># remove the first line from file</span>
</pre>
I use this little trick to change the file extension for many files at once. For example from .cxx to .cpp. Test it first without the <code>| sh</code> at the end. You can also do this with the command <code>rename</code> if installed. Or with bash builtins.
<pre># ls *.cxx | awk -F. '{print "mv "$0" "$1".cpp"}' | sh
# ls *.c | sed "s/.*/cp &amp; &amp;.$(date "+%Y%m%d")/" | sh <span class="cmt"># e.g. copy *.c to *.c.20080401</span>
# rename .cxx .cpp *.cxx                             <span class="cmt"># Rename all .cxx to cpp</span>
# for i in *.cxx; do mv $i ${i%%.cxx}.cpp; done      <span class="cmt"># with bash builtins</span>
</pre>
</div>

<div id="programming"><h1><a>Programming</a></h1>
<h2 id="cbasics">C basics</h2>
<pre>strcpy(newstr,str)                        <span class="cmt">/* copy str to newstr */</span>
expr1 ? expr2 : expr3                     <span class="cmt">/* if (expr1) expr2 else expr3 */</span>
x = (y &gt; z) ? y : z;                      <span class="cmt">/* if (y &gt; z) x = y; else x = z; */</span>
int a[]={0,1,2};                          <span class="cmt">/* Initialized array (or a[3]={0,1,2}; */</span>
int a[2][3]={{1,2,3},{4,5,6}};            <span class="cmt">/* Array of array of ints */</span>
int i = 12345;                            <span class="cmt">/* Convert in i to char str */</span>
char str[10];
sprintf(str, "%d", i);
</pre>
<h2>C example</h2>
A minimal c program simple.c:
<pre><span class="pp">#include</span> &lt;stdio.h&gt;
main() {
    <span class="keyword">int</span> number=42;
    printf("The answer is %i\n", number);  
}
</pre>
Compile with:
<pre># gcc simple.c -o simple
# ./simple
The answer is 42
</pre>

<h2 id="cppbasics">C++ basics</h2>
<pre>*pointer                                  <span class="cmt">// Object pointed to by pointer</span>
&amp;obj                                      <span class="cmt">// Address of object obj</span>
obj.x                                     <span class="cmt">// Member x of class obj (object obj)</span>
pobj-&gt;x                                   <span class="cmt">// Member x of class pointed to by pobj</span>
                                          <span class="cmt">// (*pobj).x and pobj-&gt;x are the same</span>
</pre>
<h2>C++ example</h2>
As a slightly more realistic program in C++, let's create a class in its own header (IPv4.h) and implementation (IPv4.cpp) and create a program which uses the class functionality. The class has a member to convert an IP address in integer format to the known quad format. This is a minimal c++ program with a class and multi-source compile.
<h3>IPv4 class</h3>
<h4>IPv4.h:</h4>
<pre style="page-break-inside: avoid;"><span class="pp">#ifndef</span> IPV4_H
<span class="pp">#define</span> IPV4_H
<span class="pp">#include</span> &lt;string&gt;

<span class="keyword">namespace</span> GenericUtils {                          <span class="cmt">// create a namespace
</span><span class="keyword">class</span> IPv4 {                                      <span class="cmt">// class definition
</span><span class="keyword">public</span>:
    IPv4();
    ~IPv4();
    std::string IPint_to_IPquad(<span class="keyword">unsigned</span> <span class="keyword">long</span> ip);<span class="cmt">// member interface
</span>};
} <span class="cmt">//namespace GenericUtils</span>
<span class="pp">#endif</span> <span class="cmt">// IPV4_H
</span></pre>

<h4>IPv4.cpp:</h4>
<pre style="page-break-inside: avoid;"><span class="pp">#include</span> "IPv4.h"
<span class="pp">#include</span> &lt;string&gt;
<span class="pp">#include</span> &lt;sstream&gt;
<span class="keyword">using</span> <span class="keyword">namespace</span> std;                              <span class="cmt">// use the namespaces
</span><span class="keyword">using</span> <span class="keyword">namespace</span> GenericUtils;

IPv4::IPv4() {}                                   <span class="cmt">// default constructor/destructor
</span>IPv4::~IPv4() {}
string IPv4::IPint_to_IPquad(<span class="keyword">unsigned</span> <span class="keyword">long</span> ip) {  <span class="cmt">// member implementation
</span>    ostringstream ipstr;                          <span class="cmt">// use a stringstream
</span>    ipstr &lt;&lt; ((ip &amp;0xff000000) &gt;&gt; 24)             <span class="cmt">// Bitwise right shift
</span>          &lt;&lt; "." &lt;&lt; ((ip &amp;0x00ff0000) &gt;&gt; 16)
          &lt;&lt; "." &lt;&lt; ((ip &amp;0x0000ff00) &gt;&gt; 8)
          &lt;&lt; "." &lt;&lt; ((ip &amp;0x000000ff));
    <span class="keyword">return</span> ipstr.str();
}
</pre>
<h3>The program simplecpp.cpp</h3>
<pre style="page-break-inside: avoid;"><span class="pp">#include</span> "IPv4.h"
<span class="pp">#include</span> &lt;iostream&gt;
<span class="pp">#include</span> &lt;string&gt;
<span class="keyword">using</span> <span class="keyword">namespace</span> std;

<span class="keyword">int</span> main (<span class="keyword">int</span> argc, <span class="keyword">char</span>* argv[]) {
    string ipstr;                                 <span class="cmt">// define variables
</span>    <span class="keyword">unsigned</span> <span class="keyword">long</span> ipint = 1347861486;             <span class="cmt">// The IP in integer form</span>
    GenericUtils::IPv4 iputils;                   <span class="cmt">// create an object of the class
</span>    ipstr = iputils.IPint_to_IPquad(ipint);       <span class="cmt">// call the class member
</span>    cout &lt;&lt; ipint &lt;&lt; " = " &lt;&lt; ipstr &lt;&lt; endl;      <span class="cmt">// print the result</span>

    <span class="keyword">return</span> 0;
}
</pre>

Compile and execute with:
<pre style="page-break-before: avoid;"># g++ -c IPv4.cpp simplecpp.cpp                <span class="cmt"># Compile in objects</span>
# g++ IPv4.o simplecpp.o -o simplecpp.exe      <span class="cmt"># Link the objects to final executable</span>
# ./simplecpp.exe 
1347861486 = 80.86.187.238
</pre>
Use <code>ldd</code> to check which libraries are used by the executable and where they are located. This command is also used to check if a shared library is missing or if the executable is static.
<pre># ldd /sbin/ifconfig</pre>
<h2 id="makefile">Simple Makefile</h2>
The corresponding minimal Makefile for the multi-source program is shown below. The lines with instructions <i>must begin with a tab</i>! The back slash "\" can be used to cut long lines.
<pre style="page-break-inside: avoid;"><span class="pp">CC</span> = g++
<span class="pp">CFLAGS</span> = -O
<span class="pp">OBJS</span> = IPv4.o simplecpp.o

<span class="keyword">simplecpp</span>: ${OBJS}
	${CC} -o simplecpp ${CFLAGS} ${OBJS}
<span class="keyword">clean</span>:
	rm -f ${TARGET} ${OBJS}
</pre>
</div>

<div id="onlinehelp"><h1><a>Online Help</a></h1>
<h2 id="documentation">Documentation</h2>
<table>
  <tr><td><a href="http://en.tldp.org/">Linux Documentation</a> </td><td>en.tldp.org</td></tr>
  <tr><td><a href="http://www.linuxmanpages.com/">Linux Man Pages</a> </td><td>www.linuxmanpages.com</td></tr>
  <tr><td><a href="http://www.oreillynet.com/linux/cmd/">Linux commands directory</a> </td><td>www.oreillynet.com/linux/cmd</td></tr>
  <tr><td><a href="http://linux.die.net/">Linux doc man howtos</a> </td><td>linux.die.net</td></tr>
  <tr><td><a href="http://www.freebsd.org/handbook/">FreeBSD Handbook</a> </td><td>www.freebsd.org/handbook</td></tr>
  <tr><td><a href="http://www.freebsd.org/cgi/man.cgi">FreeBSD Man Pages</a> </td><td>www.freebsd.org/cgi/man.cgi</td></tr>
  <tr><td><a href="http://www.freebsdwiki.net/">FreeBSD user wiki</a> </td><td>www.freebsdwiki.net</td></tr>
  <tr><td><a href="http://docs.sun.com/app/docs/coll/40.10">Solaris Man Pages</a> </td><td>docs.sun.com/app/docs/coll/40.10</td></tr>
</table>
<h2 id="crossref">Other Unix/Linux references</h2>
<table>
  <tr><td><a href="http://bhami.com/rosetta.html">Rosetta Stone for Unix</a> </td><td>bhami.com/rosetta.html (a Unix command translator)</td></tr>
  <tr><td><a href="http://unixguide.net/unixguide.shtml">Unix guide cross reference</a> </td><td>unixguide.net/unixguide.shtml</td></tr>
  <tr><td><a rel="nofollow" href="http://www.linuxguide.it/linux_commands_line_en.htm">Linux commands line list</a> </td><td>www.linuxguide.it/commands_list.php</td></tr>
  <tr><td><a rel="nofollow" href="http://www.pixelbeat.org/cmdline.html">Short Linux reference</a> </td><td>www.pixelbeat.org/cmdline.html</td></tr>
  <tr><td><a href="http://www.shell-fu.org/">Little command line goodies</a> </td><td>www.shell-fu.org</td></tr>
</table>
</div>

<p class="last">That's all folks!</p>

<!-- page break -->
<!-- <div class="pb" /> -->

<div class="footerlast">
This document: "Unix Toolbox revision 12" is licensed under a <a rel="nofollow" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Licence [Attribution - Share Alike]</a>. © <a href="mailto:c_at_cb.vu">Colin Barschel</a> 2007-2008. Some rights reserved.
</div>

</body>
</html>